-2

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
Stacky
  • 3
  • 5
  • Isn't the length of a unit vector always 1, by definition? `function constructUnitVector(a, b) { return 1; }` ...? – Guy Incognito Dec 09 '20 at 12:05
  • The point is to calculate the process of getting 1. – Stacky Dec 09 '20 at 12:26
  • That makes very little sense to me, but then it would be `function constructUnitVector(a, b) { const magnitude = calcHypotenuse(a, b); return magnitude / magnitude; }` – Guy Incognito Dec 09 '20 at 12:29

1 Answers1

1

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 
trincot
  • 317,000
  • 35
  • 244
  • 286