Repository navigation
Fix precision loss in variance, standard deviation and related statistics (HF-491) #1784
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
7a88902
Fix precision loss in VAR/STDEV on data with a large mean
marcin-kordas-hoc bb43a62
Compute DEVSQ, COVARIANCE, SLOPE, STEYX and the D-variance functions …
marcin-kordas-hoc f42263e
Fix overflow regressions in the double-double variance code (HF-491)
sequba d3a1bec
Fix STEYX returning 0 when the slope overflows, and return #DIV/0! fr…
sequba 92ebfbd
Keep the variance sums with a power-of-two exponent and compute AVERA…
sequba 1d0c822
Shorten the variance changelog entries (HF-491)
marcin-kordas-hoc 4c97bae
Share the x-deviation checks of SLOPE and STEYX and route AVERAGEA th…
sequba 9d88a38
Simplify the changelog entries for the variance fixes (HF-491)
sequba 6d4925e
Fold the D-variance functions through MomentsAggregate and scale the …
sequba 30a0691
Merge remote-tracking branch 'origin/develop' into fix/variance-preci…
sequba 2b3c8ab
Add a message to the equal-x #DIV/0! of SLOPE and STEYX and fix the d…
sequba e0d1e7d
Compute the STEYX residual sum of squares from the residuals themselv…
sequba 6001b6e
Describe the STEYX fix for points that lie almost on a line in the ch…
sequba 91456eb
Fix the release script
sequba File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| /** | ||
| * @license | ||
| * Copyright (c) 2025 Handsoncode. All rights reserved. | ||
| */ | ||
|
|
||
| import { | ||
| addDoubleDouble, | ||
| divideDoubleDouble, | ||
| DOUBLE_DOUBLE_ZERO, | ||
| DoubleDouble, | ||
| multiplyByPowerOfTwo, | ||
| multiplyDoubleDouble, | ||
| roundDoubleDouble, | ||
| subtractDoubleDouble, | ||
| } from './doubleDouble' | ||
|
|
||
| /** | ||
| * Sums of squared deviations and of products of deviations from the mean, for the functions built | ||
| * on them (DEVSQ, COVARIANCE, SLOPE, STEYX, DSTDEV, DVAR and their variants). | ||
| * | ||
| * The mean, the deviations and their sums are all kept in double-double and rounded once at the end, | ||
| * so the result is accurate to the last digits of the stored values even when the mean is large | ||
| * relative to the spread. | ||
| */ | ||
|
|
||
| /** | ||
| * The mean of the values. | ||
| * | ||
| * When the running total overflows, the values are summed scaled down by a power of two no smaller | ||
| * than their count, so that no partial sum can exceed the largest double, and the mean is scaled back. | ||
| * | ||
| * @param {number[]} values - a non-empty array of numbers | ||
| * @returns {DoubleDouble} the mean, without rounding to a double | ||
| */ | ||
| function mean(values: number[]): DoubleDouble { | ||
| const total = sum(values) | ||
| if (Number.isFinite(total.hi)) { | ||
| return divideDoubleDouble(total, values.length) | ||
| } | ||
| const scale = 2 ** Math.ceil(Math.log2(values.length)) | ||
| const scaledTotal = sum(values.map((value) => value / scale)) | ||
| return multiplyByPowerOfTwo(divideDoubleDouble(scaledTotal, values.length), scale) | ||
| } | ||
|
|
||
| /** | ||
| * The sum of the values. | ||
| * | ||
| * @param {number[]} values - an array of numbers | ||
| * @returns {DoubleDouble} the sum, without rounding to a double | ||
| */ | ||
| function sum(values: number[]): DoubleDouble { | ||
| return values.reduce<DoubleDouble>((total, value) => addDoubleDouble(total, {hi: value, lo: 0}), DOUBLE_DOUBLE_ZERO) | ||
| } | ||
|
|
||
| /** | ||
| * The deviations of the values from their mean. | ||
| * | ||
| * @param {number[]} values - a non-empty array of numbers | ||
| * @returns {DoubleDouble[]} `value - mean` for each value, without rounding | ||
| */ | ||
| export function deviationsFromMean(values: number[]): DoubleDouble[] { | ||
| const center = mean(values) | ||
| return values.map((value) => subtractDoubleDouble({hi: value, lo: 0}, center)) | ||
| } | ||
|
|
||
| /** | ||
| * The sum of the squared deviations of the values from their mean. | ||
| * | ||
| * @param {number[]} values - a non-empty array of numbers | ||
| * @returns {DoubleDouble} `sum((x - mean)^2)` | ||
| */ | ||
| export function sumOfSquaredDeviations(values: number[]): DoubleDouble { | ||
| const deviations = deviationsFromMean(values) | ||
| return sumOfProducts(deviations, deviations) | ||
| } | ||
|
|
||
| /** | ||
| * The sum of the products of the paired deviations of two arrays from their means. | ||
| * | ||
| * @param {number[]} first - a non-empty array of numbers | ||
| * @param {number[]} second - an array of the same length as `first` | ||
| * @returns {DoubleDouble} `sum((x - mean(x)) * (y - mean(y)))` | ||
| */ | ||
| export function sumOfProductsOfDeviations(first: number[], second: number[]): DoubleDouble { | ||
| return sumOfProducts(deviationsFromMean(first), deviationsFromMean(second)) | ||
| } | ||
|
|
||
| /** | ||
| * The variance of the values: the sum of squared deviations divided by `n - deltaDegreesOfFreedom`. | ||
| * | ||
| * @param {number[]} values - a non-empty array of numbers | ||
| * @param {number} deltaDegreesOfFreedom - 0 for the population variance, 1 for the sample variance | ||
| * @returns {number} the variance, rounded once to a double | ||
| */ | ||
| export function variance(values: number[], deltaDegreesOfFreedom: number): number { | ||
| return roundDoubleDouble(divideDoubleDouble(sumOfSquaredDeviations(values), values.length - deltaDegreesOfFreedom)) | ||
| } | ||
|
|
||
| /** | ||
| * The covariance of two arrays: the sum of products of deviations divided by `n - deltaDegreesOfFreedom`. | ||
| * | ||
| * @param {number[]} first - a non-empty array of numbers | ||
| * @param {number[]} second - an array of the same length as `first` | ||
| * @param {number} deltaDegreesOfFreedom - 0 for the population covariance, 1 for the sample covariance | ||
| * @returns {number} the covariance, rounded once to a double | ||
| */ | ||
| export function covariance(first: number[], second: number[], deltaDegreesOfFreedom: number): number { | ||
| return roundDoubleDouble(divideDoubleDouble(sumOfProductsOfDeviations(first, second), first.length - deltaDegreesOfFreedom)) | ||
| } | ||
|
|
||
| /** | ||
| * The sum of the products of paired double-doubles. | ||
| * | ||
| * @param {DoubleDouble[]} first - the first factors | ||
| * @param {DoubleDouble[]} second - the second factors, of the same length | ||
| * @returns {DoubleDouble} `sum(first[i] * second[i])` | ||
| */ | ||
| export function sumOfProducts(first: DoubleDouble[], second: DoubleDouble[]): DoubleDouble { | ||
| return first.reduce<DoubleDouble>((sum, deviation, index) => addDoubleDouble(sum, multiplyDoubleDouble(deviation, second[index])), DOUBLE_DOUBLE_ZERO) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,219 @@ | ||
| /** | ||
| * @license | ||
| * Copyright (c) 2025 Handsoncode. All rights reserved. | ||
| */ | ||
|
|
||
| /** | ||
| * A number represented as the unevaluated sum `hi + lo` of two doubles (double-double arithmetic). | ||
| * It carries about 106 bits of significand instead of 53, so sums and products keep the low-order | ||
| * digits that plain doubles round away. After `twoSum`, `twoProduct`, `addDoubleDouble` and | ||
| * `divideDoubleDouble`, `|lo|` is at most half an ulp of `hi`; products of double-doubles are left | ||
| * unnormalized. | ||
| * | ||
| * Used where a result is the small difference of large accumulated quantities, such as a sum of | ||
| * squared deviations. The building blocks are the error-free transformations TwoSum and TwoProduct | ||
| * (splitting a factor by 2^27 + 1), which need no fused multiply-add. | ||
| */ | ||
| export interface DoubleDouble { | ||
| readonly hi: number, | ||
| readonly lo: number, | ||
| } | ||
|
|
||
| export const DOUBLE_DOUBLE_ZERO: DoubleDouble = {hi: 0, lo: 0} | ||
|
|
||
| /** Splitting constant for binary64: 2^27 + 1. */ | ||
| const SPLITTER = 134217729 | ||
|
|
||
| /** The largest magnitude that can be multiplied by `SPLITTER` without overflowing (2^996). */ | ||
| const SPLIT_LIMIT = 2 ** 996 | ||
|
|
||
| /** | ||
| * The largest product magnitude for which the product of the split high halves (at most `|a * b|` | ||
| * times (1 + 2^-26)^2) cannot overflow (2^1023). | ||
| */ | ||
| const PRODUCT_LIMIT = 2 ** 1023 | ||
|
|
||
| /** | ||
| * An exact power-of-two scale (2^53) for the larger factor of a product above `PRODUCT_LIMIT` or with | ||
| * a factor above `SPLIT_LIMIT`, so that splitting it cannot overflow. | ||
| */ | ||
| const FACTOR_SCALE = 2 ** 53 | ||
|
|
||
| /** | ||
| * The largest dividend magnitude that `divideDoubleDouble` and `divideDoubleDoubles` divide directly | ||
| * (2^1000). Above it, the quotient times the divisor can round to infinity, so the dividend is scaled | ||
| * down by `DIVIDEND_SCALE` first. | ||
| */ | ||
| const DIVIDEND_LIMIT = 2 ** 1000 | ||
|
|
||
| /** An exact power-of-two scale for dividends above `DIVIDEND_LIMIT` (2^64). */ | ||
| const DIVIDEND_SCALE = 2 ** 64 | ||
|
|
||
| /** | ||
| * The exact sum of two doubles, as a double-double (TwoSum). | ||
| * | ||
| * The rounding error is computed from the addend of larger magnitude (Fast2Sum), which is exact and, | ||
| * unlike the branch-free form, cannot overflow while the sum is finite. | ||
| * | ||
| * @param {number} a - first addend | ||
| * @param {number} b - second addend | ||
| * @returns {DoubleDouble} `a + b` with no rounding error | ||
| */ | ||
| export function twoSum(a: number, b: number): DoubleDouble { | ||
| const hi = a + b | ||
| return {hi, lo: Math.abs(a) >= Math.abs(b) ? b - (hi - a) : a - (hi - b)} | ||
| } | ||
|
|
||
| /** | ||
| * The exact product of two doubles, as a double-double (TwoProduct). | ||
| * | ||
| * When a factor exceeds 2^996 or the product exceeds 2^1023, the larger factor is scaled by 2^-53 | ||
| * (exactly) so the splitting cannot overflow, and the error term is scaled back. | ||
| * | ||
| * @param {number} a - first factor | ||
| * @param {number} b - second factor | ||
| * @returns {DoubleDouble} `a * b`, with no rounding error whenever the product is finite and at least | ||
| * 2^-969 in magnitude; an infinite or NaN product has `lo` 0 | ||
| */ | ||
| export function twoProduct(a: number, b: number): DoubleDouble { | ||
| const hi = a * b | ||
| if (Math.abs(a) <= SPLIT_LIMIT && Math.abs(b) <= SPLIT_LIMIT && Math.abs(hi) <= PRODUCT_LIMIT) { | ||
| return {hi, lo: productError(a, b, hi)} | ||
| } | ||
| if (!Number.isFinite(hi)) { | ||
| return {hi, lo: 0} | ||
| } | ||
| const [larger, smaller] = Math.abs(a) >= Math.abs(b) ? [a, b] : [b, a] | ||
| const largerScaled = larger / FACTOR_SCALE | ||
| return {hi, lo: productError(largerScaled, smaller, largerScaled * smaller) * FACTOR_SCALE} | ||
| } | ||
|
|
||
| /** | ||
| * The rounding error of `a * b`, where `hi` is `a * b` rounded (Dekker's product with Veltkamp | ||
| * splitting). Exact when both factors are at most `SPLIT_LIMIT` and `|hi|` is at most `PRODUCT_LIMIT`. | ||
| * | ||
| * @param {number} a - first factor | ||
| * @param {number} b - second factor | ||
| * @param {number} hi - `a * b` rounded to a double | ||
| * @returns {number} `a * b - hi` | ||
| */ | ||
| function productError(a: number, b: number, hi: number): number { | ||
| const aScaled = SPLITTER * a | ||
| const aHigh = aScaled - (aScaled - a) | ||
| const aLow = a - aHigh | ||
| const bScaled = SPLITTER * b | ||
| const bHigh = bScaled - (bScaled - b) | ||
| const bLow = b - bHigh | ||
| return ((aHigh * bHigh - hi) + aHigh * bLow + aLow * bHigh) + aLow * bLow | ||
| } | ||
|
cursor[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| /** | ||
| * Sum of two double-doubles. | ||
| * | ||
| * @param {DoubleDouble} x - first addend | ||
| * @param {DoubleDouble} y - second addend | ||
| * @returns {DoubleDouble} `x + y`; a sum that is infinite or NaN is the plain double sum | ||
| */ | ||
| export function addDoubleDouble(x: DoubleDouble, y: DoubleDouble): DoubleDouble { | ||
| const sum = twoSum(x.hi, y.hi) | ||
| if (!Number.isFinite(sum.hi)) { | ||
| return {hi: sum.hi, lo: 0} | ||
| } | ||
| const lo = sum.lo + x.lo + y.lo | ||
| const hi = sum.hi + lo | ||
| return {hi, lo: lo - (hi - sum.hi)} | ||
| } | ||
|
|
||
| /** | ||
| * Difference of two double-doubles. | ||
| * | ||
| * @param {DoubleDouble} x - minuend | ||
| * @param {DoubleDouble} y - subtrahend | ||
| * @returns {DoubleDouble} `x - y`; a difference that is infinite or NaN is the plain double difference | ||
| */ | ||
| export function subtractDoubleDouble(x: DoubleDouble, y: DoubleDouble): DoubleDouble { | ||
| return addDoubleDouble(x, {hi: -y.hi, lo: -y.lo}) | ||
| } | ||
|
|
||
| /** | ||
| * Product of two double-doubles. | ||
| * | ||
| * @param {DoubleDouble} x - first factor | ||
| * @param {DoubleDouble} y - second factor | ||
| * @returns {DoubleDouble} `x * y` | ||
| */ | ||
| export function multiplyDoubleDouble(x: DoubleDouble, y: DoubleDouble): DoubleDouble { | ||
| const product = twoProduct(x.hi, y.hi) | ||
| return {hi: product.hi, lo: product.lo + x.hi * y.lo + x.lo * y.hi} | ||
| } | ||
|
|
||
| /** | ||
| * Product of a double-double and a double. | ||
| * | ||
| * @param {DoubleDouble} x - double-double factor | ||
| * @param {number} k - double factor | ||
| * @returns {DoubleDouble} `x * k` | ||
| */ | ||
| export function scaleDoubleDouble(x: DoubleDouble, k: number): DoubleDouble { | ||
| const product = twoProduct(x.hi, k) | ||
| return {hi: product.hi, lo: product.lo + x.lo * k} | ||
| } | ||
|
|
||
| /** | ||
| * Quotient of a double-double and a double. | ||
| * | ||
| * @param {DoubleDouble} x - dividend | ||
| * @param {number} k - divisor | ||
| * @returns {DoubleDouble} `x / k` | ||
| */ | ||
| export function divideDoubleDouble(x: DoubleDouble, k: number): DoubleDouble { | ||
| if (Math.abs(x.hi) > DIVIDEND_LIMIT && Number.isFinite(x.hi)) { | ||
| return multiplyByPowerOfTwo(divideDoubleDouble(multiplyByPowerOfTwo(x, 1 / DIVIDEND_SCALE), k), DIVIDEND_SCALE) | ||
| } | ||
| const quotient = x.hi / k | ||
| const product = twoProduct(quotient, k) | ||
| return twoSum(quotient, ((x.hi - product.hi) - product.lo + x.lo) / k) | ||
| } | ||
|
|
||
| /** | ||
| * Quotient of two double-doubles. | ||
| * | ||
| * A zero or non-finite divisor, or a non-finite quotient, gives the plain double quotient, so infinities, | ||
| * zeros and NaNs are the same as in ordinary arithmetic. | ||
| * | ||
| * @param {DoubleDouble} x - dividend | ||
| * @param {DoubleDouble} y - divisor | ||
| * @returns {DoubleDouble} `x / y` | ||
| */ | ||
| export function divideDoubleDoubles(x: DoubleDouble, y: DoubleDouble): DoubleDouble { | ||
| const quotient = x.hi / y.hi | ||
| if (!Number.isFinite(quotient) || !Number.isFinite(y.hi)) { | ||
| return {hi: quotient, lo: 0} | ||
| } | ||
| if (Math.abs(x.hi) > DIVIDEND_LIMIT) { | ||
| return multiplyByPowerOfTwo(divideDoubleDoubles(multiplyByPowerOfTwo(x, 1 / DIVIDEND_SCALE), y), DIVIDEND_SCALE) | ||
| } | ||
| const remainder = subtractDoubleDouble(x, scaleDoubleDouble(y, quotient)) | ||
| return twoSum(quotient, remainder.hi / y.hi) | ||
| } | ||
|
|
||
| /** | ||
| * Product of a double-double and a power of two, which is exact unless it overflows or underflows. | ||
| * | ||
| * @param {DoubleDouble} x - double-double factor | ||
| * @param {number} powerOfTwo - a power of two | ||
| * @returns {DoubleDouble} `x * powerOfTwo` | ||
| */ | ||
| export function multiplyByPowerOfTwo(x: DoubleDouble, powerOfTwo: number): DoubleDouble { | ||
| return {hi: x.hi * powerOfTwo, lo: x.lo * powerOfTwo} | ||
| } | ||
|
|
||
| /** | ||
| * Rounds a double-double to the nearest double. | ||
| * | ||
| * @param {DoubleDouble} x - the value to round | ||
| * @returns {number} `x` as a double | ||
| */ | ||
| export function roundDoubleDouble(x: DoubleDouble): number { | ||
| return x.hi + x.lo | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| /** | ||
| * @license | ||
| * Copyright (c) 2025 Handsoncode. All rights reserved. | ||
| */ | ||
|
|
||
| import {Maybe} from '../../Maybe' | ||
|
|
||
| /** | ||
| * The sum and the count of a set of numbers, composable so that the value of a range can be cached | ||
| * and reused for a larger range. | ||
| */ | ||
| export class AverageResult { | ||
| public static empty = new AverageResult(0, 0) | ||
|
|
||
| constructor( | ||
| public readonly sum: number, | ||
| public readonly count: number, | ||
| ) {} | ||
|
|
||
| public static single(arg: number): AverageResult { | ||
| return new AverageResult(arg, 1) | ||
| } | ||
|
|
||
| public compose(other: AverageResult) { | ||
| return new AverageResult(this.sum + other.sum, this.count + other.count) | ||
| } | ||
|
|
||
| public averageValue(): Maybe<number> { | ||
| if (this.count > 0) { | ||
| return this.sum / this.count | ||
| } else { | ||
| return undefined | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.