|
| 1 | +/** |
| 2 | + * Calculates the standard deviation of values in a Series. |
| 3 | + * |
| 4 | + * @param {Series} series - Series instance |
| 5 | + * @param {Object} [options={}] - Options object |
| 6 | + * @param {boolean} [options.population=false] - If true, calculates population standard deviation (using n as divisor) |
| 7 | + * @returns {number|null} - Standard deviation or null if no valid values |
| 8 | + */ |
| 9 | +export function std(series, options = {}) { |
| 10 | + const values = series.toArray(); |
| 11 | + if (values.length === 0) return null; |
| 12 | + |
| 13 | + // Filter only numeric values (not null, not undefined, not NaN) |
| 14 | + const numericValues = values |
| 15 | + .filter( |
| 16 | + (value) => |
| 17 | + value !== null && value !== undefined && !Number.isNaN(Number(value)), |
| 18 | + ) |
| 19 | + .map((value) => Number(value)); |
| 20 | + |
| 21 | + // If there are no numeric values, return null |
| 22 | + if (numericValues.length === 0) return null; |
| 23 | + |
| 24 | + // If there is only one value, the standard deviation is 0 |
| 25 | + if (numericValues.length === 1) return 0; |
| 26 | + |
| 27 | + // Calculate the mean value |
| 28 | + const mean = |
| 29 | + numericValues.reduce((sum, value) => sum + value, 0) / numericValues.length; |
| 30 | + |
| 31 | + // Calculate the sum of squared differences from the mean |
| 32 | + const sumSquaredDiffs = numericValues.reduce((sum, value) => { |
| 33 | + const diff = value - mean; |
| 34 | + return sum + diff * diff; |
| 35 | + }, 0); |
| 36 | + |
| 37 | + // Calculate the variance |
| 38 | + // If population=true, use n (biased estimate for the population) |
| 39 | + // Otherwise, use n-1 (unbiased estimate for the sample) |
| 40 | + const divisor = options.population |
| 41 | + ? numericValues.length |
| 42 | + : numericValues.length - 1; |
| 43 | + const variance = sumSquaredDiffs / divisor; |
| 44 | + |
| 45 | + // Return the standard deviation (square root of variance) |
| 46 | + return Math.sqrt(variance); |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | + * Registers the std method on Series prototype |
| 51 | + * @param {Class} Series - Series class to extend |
| 52 | + */ |
| 53 | +export function register(Series) { |
| 54 | + if (!Series.prototype.std) { |
| 55 | + Series.prototype.std = function (options) { |
| 56 | + return std(this, options); |
| 57 | + }; |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +export default { std, register }; |
0 commit comments