-
-
Notifications
You must be signed in to change notification settings - Fork 151
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(vectors): add covariance(), correlation() fns
- Loading branch information
1 parent
9c34793
commit b8d661d
Showing
2 changed files
with
48 additions
and
0 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 |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import type { ReadonlyVec } from "./api"; | ||
import { center } from "./center"; | ||
import { mag } from "./mag"; | ||
import { mul } from "./mul"; | ||
import { sum } from "./sum"; | ||
|
||
/** | ||
* Computes the Pearson correlation coefficient between `a` and `b`. Returns | ||
* `undefined` if the denominator (see below) is zero. | ||
* | ||
* @remarks | ||
* ```text | ||
* sum(a' * b') / (mag(a') * mag(b')) | ||
* ``` | ||
* | ||
* ...where `a'` and `b'` are {@link center}'ed versions of given input vectors. | ||
* | ||
* References: | ||
* - https://en.wikipedia.org/wiki/Correlation | ||
* - https://www.youtube.com/watch?v=2bcmklvrXTQ | ||
* | ||
* @param a | ||
* @param b | ||
*/ | ||
export const correlation = (a: ReadonlyVec, b: ReadonlyVec) => { | ||
a = center([], a); | ||
b = center([], b); | ||
const m = mag(a) * mag(b); | ||
return m !== 0 ? sum(mul(null, a, b)) / m : undefined; | ||
}; |
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 |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import type { ReadonlyVec } from "./api"; | ||
import { center } from "./center"; | ||
import { mul } from "./mul"; | ||
import { sum } from "./sum"; | ||
|
||
/** | ||
* Computes the covariance coefficient between the two given vectors. | ||
* | ||
* @remarks | ||
* References: | ||
* - https://en.wikipedia.org/wiki/Covariance | ||
* - https://www.youtube.com/watch?v=2bcmklvrXTQ | ||
* | ||
* @param a | ||
* @param b | ||
*/ | ||
export const covariance = (a: ReadonlyVec, b: ReadonlyVec) => | ||
sum(mul(null, center([], a), center([], b))) / (a.length - 1); |