Search code examples
javascriptfunctionhypotenuse

Unit Vector Function


I am trying to calculate the unit vector in R², using JavaScript.

I expected an output of 1, but I get 1.949.6. what did I miss in this implementation?

    function calcHypotenuse(a, b) {
        return (Math.sqrt((a * a) + (b * b)));
    }
      
    function contructUnitVector(a, b) {
        const magitude = calcHypotenuse(a, b);
        return (Math.sqrt(a + b / magitude)); 
    }
    
    console.log(contructUnitVector(3, 4)); // 1.949, expected 1


Solution

  • A unit vector is not a number, but a ... vector. If you are given the coordinates of a vector in R², then you can get the corresponding unit vector as follows:

    function vectorSize(x, y) {
       return Math.sqrt(x * x + y * y);
    }
         
    function unitVector(x, y) {
       const magnitude = vectorSize(x, y);
       // We need to return a vector here, so we return an array of coordinates:
       return [x / magnitude, y / magnitude]; 
    }
       
    let unit = unitVector(3, 4);
    
    console.log("Unit vector has coordinates: ", ...unit);
    console.log("It's magnitude is: ", vectorSize(...unit)); // Always 1