Skip to content

Commit

Permalink
feat(vectors): add covariance(), correlation() fns
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Aug 29, 2021
1 parent 9c34793 commit b8d661d
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
30 changes: 30 additions & 0 deletions packages/vectors/src/correlation.ts
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;
};
18 changes: 18 additions & 0 deletions packages/vectors/src/covariance.ts
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);

0 comments on commit b8d661d

Please sign in to comment.