-
Notifications
You must be signed in to change notification settings - Fork 11.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
69a2444
commit 5d9c484
Showing
1 changed file
with
12 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
``` |