Vector angle

JavaScript, Math · Jan 7, 2021

Calculates the angle (theta) between two vectors.

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

More like this

  • JavaScript Geometric Operations

    Learn how to perform some basic geometric operations in JavaScript with this collection of snippets.

    Collection · 4 snippets

  • Vector distance

    Calculates the distance between two vectors.

    JavaScript, Math · Dec 28, 2020

  • Euclidean distance

    Calculates the distance between two points in any number of dimensions.

    JavaScript, Math · Dec 28, 2020

  • Greatest common divisor

    Calculates the greatest common divisor between two or more numbers/arrays.

    JavaScript, Math · Dec 29, 2020