-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstd.js
More file actions
61 lines (52 loc) · 1.9 KB
/
std.js
File metadata and controls
61 lines (52 loc) · 1.9 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Calculates the standard deviation of values in a Series.
*
* @param {Series} series - Series instance
* @param {Object} [options={}] - Options object
* @param {boolean} [options.population=false] - If true, calculates population standard deviation (using n as divisor)
* @returns {number|null} - Standard deviation or null if no valid values
*/
export function std(series, options = {}) {
const values = series.toArray();
if (values.length === 0) return null;
// Filter only numeric values (not null, not undefined, not NaN)
const numericValues = values
.filter(
(value) =>
value !== null && value !== undefined && !Number.isNaN(Number(value)),
)
.map((value) => Number(value));
// If there are no numeric values, return null
if (numericValues.length === 0) return null;
// If there is only one value, the standard deviation is 0
if (numericValues.length === 1) return 0;
// Calculate the mean value
const mean =
numericValues.reduce((sum, value) => sum + value, 0) / numericValues.length;
// Calculate the sum of squared differences from the mean
const sumSquaredDiffs = numericValues.reduce((sum, value) => {
const diff = value - mean;
return sum + diff * diff;
}, 0);
// Calculate the variance
// If population=true, use n (biased estimate for the population)
// Otherwise, use n-1 (unbiased estimate for the sample)
const divisor = options.population
? numericValues.length
: numericValues.length - 1;
const variance = sumSquaredDiffs / divisor;
// Return the standard deviation (square root of variance)
return Math.sqrt(variance);
}
/**
* Registers the std method on Series prototype
* @param {Class} Series - Series class to extend
*/
export function register(Series) {
if (!Series.prototype.std) {
Series.prototype.std = function (options) {
return std(this, options);
};
}
}
export default { std, register };