mathajax

Vector - magnitude

The java code finds magnitude of a vector which can be 2 Dimension or 3 Dimension or any number of dimension.

A java class Vector defined with two member functions to calculate magnitude of a vector in double or integer datatype.

As the both member function declared with keyword static,  we can access the member function by class class name.  we do not need to create object to the class.


Magnitude of 2D vector Equation





Magnitude of N-Dimensional vector Equation





Example Calculation

This is an example calculation shown below that explains how to find a vector magnitude. A vector,array of elements declared and initialized in java using one dimensional array.
    int A[] = { 2 ,3 };    // 2D vector A 
   
   find a magnitude for vector A 
   
   |A|   =  sqrt (  A[0]^2  +  A[1]^2  )
   
               = sqrt ( 2^2  + 3^2 );
                  
        = sqrt ( 4  + 9 ); 
      
        = sqrt ( 13 );
      
      |A|  = 3.605      
      
     magnitude of  vector A=[2,3] is 3.605     




package math;

import java.util.Arrays;

public class Vector {

 
 public static double magnitude(int vec[]) {
 
  double mag =0;
  for (int n=0;n<vec.length;n++)
   mag  +=  Math.pow(vec[n],2);
  
  return Math.sqrt(mag);
 }
 
 
 public static double magnitude(double vec[]) {
  
  double mag =0;
  for (int n=0;n<vec.length;n++)
   mag  +=  Math.pow(vec[n],2);
  
  return Math.sqrt(mag);
 }
 
 public static void main(String[] args) 
 {    
 int elem[] =  {6,8};          
 double mag = Vector.magnitude(elem);
    
        System.out.println("\n Find magnitude of 2D vector");
    
 System.out.println("\n Given 2D integer vector");
 System.out.println(Arrays.toString(elem));
 System.out.println("Magnitue :" + mag);
    
 double elem2[] =  {2.6,4.5};          
 double mag2 = Vector.magnitude(elem2);           
 System.out.println("\n Given 2D double vector ");
 System.out.println(Arrays.toString(elem2));    
 System.out.println("Magnitue :" + mag2);
          
    
 System.out.println("\n Find magnitude of 2D vector");
 double elem3[] =  {2.6,4.5,6.8};          
 double mag3 = Vector.magnitude(elem3);           
 System.out.println("n Given 3D double vector ");
 System.out.println(Arrays.toString(elem3));    
 System.out.println("Magnitue :" + mag3);
        
 }

}


Output
Find magnitude of 2D vector

Given 2D integer vector
[6, 8]
Magnitue :10.0

Given 2D double vector 
[2.6, 4.5]
Magnitue :5.197114584074513

 Find magnitude of 3D vector

Given 3D double vector 
[2.6, 4.5, 6.8]
Magnitue :8.558621384311845

Comments

Popular posts from this blog

Solving System of Linear Equations by Gauss Jordan Elimination

Matrix Forward and Back Substitution

Solve System of Linear Equations by LU Decompose

Matrix Determinant by Upper Triangular Matrix

Chebyshev distance between two points