mathajax

Vector norm

To measure the length of a vector is called the vector norm, in which length is measured from the origin (0,0) to the vector point on a plane. The following equation are used to measure length of a vector by 1-norm and 2-norm respectively.

1-norm Equation
The vector length is measured by the absolute sum of the vector's elements
norm1
or
norm1
2-norm Equation
The 2-norm is also called as euclidean norm and is measured by root of squared sum of the vector's elements.

norm2
or
norm2

Java code - vector norm

The following Java code finds a vector norm1 and norm2. A vector is defined in Java program by a integer array and a double array.


import java.util.Arrays;

public class Vector
 {
 
  public static double norm1(double vec[]) {  
  double nrm =0.0;
  for(int n=0;n<vec.length;n++)
   nrm += Math.abs(vec[n]);
  return nrm;
 }
 
  public static int norm1(int vec[]) {  
  int nrm =0;
  for(int n=0;n<vec.length;n++)
   nrm += Math.abs(vec[n]);
  return nrm;
 }
  
  public static double norm2 (double vec[]) {
   
   double nrm2 =0;
   for(int n=0;n<vec.length;n++)
  nrm2 += vec[n]*vec[n];  
   return Math.sqrt(nrm2);
  }
  
  public static double norm2(int vec[]) {
   int nrm2 =0;
   for(int n=0;n<vec.length;n++)
  nrm2 += vec[n]*vec[n];  
   return Math.sqrt(nrm2);
  }
 
  public static void main(String[] args) 
   {  
 System.out.println("\n Find a vector norm1 and norm2n");
 double U[]={5.0, 1.2, 2.0};      
 System.out.println( "n vector U"   );
 System.out.println( Arrays.toString(U)  );
 double nrm = Vector.norm1(U);
 System.out.println( "Vector U norm1 :" + nrm );
 double nrm2 = Vector.norm2(U);
 System.out.println( "Vector U norm2 :" + nrm2 );
  
 int V[] = {2, 5, 4};
 System.out.println( "\n vector V"   );
 System.out.println( Arrays.toString(V)  );
 int inrm = Vector.norm1(V);
 System.out.println( "vector V norm :" + inrm );           
 double inrm2 = Vector.norm2(V);
 System.out.println( "vector V norm2 :" + inrm2 );
    
  }

}


Output
Find a vector norm1 and norm2

 vector U
[5.0, 1.2, 2.0]
Vector U norm1 :8.2
Vector U norm2 :5.5172

 vector V
[2, 5, 4]
vector V norm1 :11
vector V norm2 :6.7082

Comments

Popular posts from this blog

Matrix Forward and Back Substitution

Chebyshev distance between two points

Solve System of Linear Equations by LU Decompose

Complex number Multiplication and Division

Matrix Determinant, Matrix Adjoint and Matrix Inverse