Update vectorAngle.md

This commit is contained in:
Angelos Chalaris
2020-04-16 23:18:18 +03:00
committed by GitHub
parent eaf471dec9
commit 275c5e61f5

View File

@ -1,28 +1,23 @@
--- ---
title: vectorAngle title: vectorAngle
tags: math, beginner tags: math,beginner
--- ---
Returns the angle (theta) value between two vectors. Returns the angle (theta) between two vectors.
Use `Math.trunc()` to convert the half of `length` to integer.
Use `Array.prototype.slice()` slice the incoming array into 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 `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 arccos and get the theta. Use `Math.acos()` to calculate the arccos and get the theta value.
```js ```js
const vectorAngle = (...x) =>{ const vectorAngle = (x, y) => {
let half = Math.trunc(x.length / 2); let mX = Math.sqrt(x.reduce((acc, n) => acc + Math.pow(n, 2), 0));
let [a, b] = [x.slice(0, half), x.slice(half)]; let mY = Math.sqrt(y.reduce((acc, n) => acc + Math.pow(n, 2), 0));
let magnitudeOfA = Math.sqrt(a.reduce((total, num) => {return total + Math.pow(num, 2);}, 0)); return Math.acos(x.reduce((acc, n, i) => acc + n * y[i], 0) / (mX * mY));
let magnitudeOfB = Math.sqrt(b.reduce((total, num) => {return total + Math.pow(num, 2);}, 0));
let scalar = a.reduce((total, num, i)=>{return total + (num * b[i])}, 0);
return Math.acos(scalar / (magnitudeOfA * magnitudeOfB));
}; };
``` ```
```js ```js
vectorAngle(3,4,4,3); // 0.283794109208328 vectorAngle([3, 4], [4, 3]); // 0.283794109208328
``` ```