Skip to content

Commit

Permalink
Tipify vector-angle
Browse files Browse the repository at this point in the history
  • Loading branch information
Chalarangelo committed May 19, 2024
1 parent 69a2444 commit 5d9c484
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions content/snippets/js/s/vector-angle.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
---
title: Vector angle
type: snippet
title: Calculate the angle between two vectors in JavaScript
shortTitle: Vector angle
type: tip
language: javascript
tags: [math]
cover: purple-pier
dateModified: 2021-01-08
excerpt: Learn how to calculate the angle (theta) between two vectors in JavaScript.
dateModified: 2024-05-16
---

Calculates the angle (theta) between two vectors.
Given two vectors, you can calculate the angle between them using a few simple math operations. All you need to do is calculate the magnitude of each vector, the scalar product of the two vectors and use the arccosine function to get the **theta** value.

- 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.
Simply put, you can use `Math.hyptot()` to calculate the **magnitude** of each vector, then multiply the corresponding elements of the two vectors and sum them up. Then, use `Array.prototype.reduce()` to calculate the **scalar product** of the two vectors. Finally, divide the scalar product by the product of the magnitudes of the two vectors and pass the result to `Math.acos()` to get the **angle in radians**.

```js
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));
};
const vectorAngle = (x, y) =>
Math.acos(
x.reduce((acc, n, i) => acc + n * y[i], 0) /
(Math.hypot(...x) * Math.hypot(...y))
);

vectorAngle([3, 4], [4, 3]); // 0.283794109208328
```

0 comments on commit 5d9c484

Please sign in to comment.