-
Notifications
You must be signed in to change notification settings - Fork 12
/
xVariance.ts
41 lines (35 loc) · 909 Bytes
/
xVariance.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { NumberArray } from 'cheminfo-types';
import { isAnyArray } from 'is-any-array';
import { xMean } from './xMean';
export interface XVarianceOptions {
/** Unbiased option
* @default true
*/
unbiased?: boolean;
/** Mean of the data
* @default mean calculated
*/
mean?: number;
}
/** Finds the variance of the data
*
* @param values - the values of the array
* @param options - options
* @returns variance
*/
export function xVariance(values: NumberArray, options: XVarianceOptions = {}) {
if (!isAnyArray(values)) {
throw new TypeError('input must be an array');
}
const { unbiased = true, mean = xMean(values) } = options;
let sqrError = 0;
for (let i = 0; i < values.length; i++) {
const x = values[i] - mean;
sqrError += x * x;
}
if (unbiased) {
return sqrError / (values.length - 1);
} else {
return sqrError / values.length;
}
}