Menu

gitpiper

vectorAngle javascript Code Snippet in 2024

mathbeginner

Last Updated: 4 December 2024

Calculates the angle (theta) between two vectors.

  • Use Array.prototype.reduce(), Math.pow() and Math.sqrt() to calculate the magnitude of each vector and the scalar product of the two vectors.
  • Use Math.acos() to calculate the arccosine and get the theta value.
const vectorAngle = (x, y) => { let mX = Math.sqrt(x.reduce((acc, n) => acc + Math.pow(n, 2), 0)); let mY = Math.sqrt(y.reduce((acc, n) => acc + Math.pow(n, 2), 0)); return Math.acos(x.reduce((acc, n, i) => acc + n * y[i], 0) / (mX * mY)); };
vectorAngle([3, 4], [4, 3]); // 0.283794109208328

javascript snippet similar to vectorAngle For You in December 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️