"how numbers are stored and used in computers"
The angle between two vectors can be computed using the dot product. If
In JavaScript, we can implement a simple angle
function to compute the angle between two vectors.
code.js1function angle(u, v) { 2 const dotProd = dotProduct(u, v); 3 const magU = magnitude(u); 4 const magV = magnitude(v); 5 if (magU === 0 || magV === 0) { 6 throw new Error("Cannot compute angle with zero magnitude vector."); 7 } 8 9 const cosTheta = dotProd / (magU * magV); 10 11 // Ensure the value is within the valid range for acos 12 if (cosTheta < -1 || cosTheta > 1) { 13 throw new Error("Numerical error: cosine value out of range."); 14 } 15 16 return Math.acos(cosTheta); 17} 18 19function magnitude(v) { 20 return Math.sqrt(v.reduce((sum, e) => sum + e ** 2, 0)); 21} 22 23function dotProduct(u, v) { 24 return u.reduce((sum, value, index) => sum + value * v[index], 0); 25} 26 27const u = [1, 2, 3]; 28const v = [4, 5, 6]; 29 30const theta = angle(u, v); 31console.log(theta);