diff --git a/packages/vectors/src/correlation.ts b/packages/vectors/src/correlation.ts new file mode 100644 index 0000000000..9321f931c6 --- /dev/null +++ b/packages/vectors/src/correlation.ts @@ -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; +}; diff --git a/packages/vectors/src/covariance.ts b/packages/vectors/src/covariance.ts new file mode 100644 index 0000000000..78ccfdcb24 --- /dev/null +++ b/packages/vectors/src/covariance.ts @@ -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);