Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
- Fixed the `AVERAGEIF` function returning a division-by-zero error when the calculated average was `0`. [#1733](https://github.com/handsontable/hyperformula/pull/1733)
- Fixed the localized names of `VSTACK` and `HSTACK` in 14 language packs to match Microsoft Excel. [#1748](https://github.com/handsontable/hyperformula/pull/1748)
- Fixed the MAXPOOL and MEDIANPOOL functions throwing an uncaught `TypeError` instead of returning the `#VALUE!` error when the range dimensions are not a whole multiple of the window size and the stride. [#1718](https://github.com/handsontable/hyperformula/pull/1718)
- Fixed the variance and standard deviation functions (`VAR.S`, `VAR.P`, `STDEV.S`, `STDEV.P`, `VARA`, `VARPA`, `STDEVA`, `STDEVPA`, their legacy names, and `SUBTOTAL` modes 7, 8, 10, 11, 107, 108, 110 and 111) losing all precision on data with a large mean and a small spread, where they returned `0`, `#NUM!`, or a negative variance. They now return the variance of the stored values accurate to about the last digit. [#1784](https://github.com/handsontable/hyperformula/pull/1784)
- Fixed `DEVSQ`, `COVARIANCE.P`, `COVARIANCE.S` (and their aliases `COVAR`, `COVARIANCEP` and `COVARIANCES`), `SLOPE`, `STEYX`, `DSTDEV`, `DSTDEVP`, `DVAR` and `DVARP` losing digits when the values use all 15 significant digits and their mean is large relative to their spread (for example, `STEYX` returned `0.0187` instead of `0.00623` and `SLOPE` returned `1000.37` instead of `1000.53` for three values near `100000000000`). They now return results accurate to the last digits of the stored values. `STEYX` no longer returns `#NUM!` for points that lie exactly on a line, `SLOPE` and `STEYX` return `#DIV/0!` when all the x values are equal, and `#NUM!` instead of an arbitrary number when the sum of squared deviations of the x values overflows. [#1798](https://github.com/handsontable/hyperformula/pull/1798)
Comment thread
sequba marked this conversation as resolved.
Resolved
- Fixed the `MOD` function returning a remainder with the sign of the dividend instead of the sign of the divisor, which made the results differ from Excel and Google Sheets for arguments with opposite signs (e.g. `=MOD(-3, 12)` now returns `9` instead of `-3`). [#1747](https://github.com/handsontable/hyperformula/issues/1747)

## [3.4.0] - 2026-08-10
Expand Down
120 changes: 120 additions & 0 deletions src/interpreter/deviationSums.ts
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)
}
219 changes: 219 additions & 0 deletions src/interpreter/doubleDouble.ts
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
}
Comment thread
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
}
35 changes: 35 additions & 0 deletions src/interpreter/plugin/AverageResult.ts
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
}
}
}
Loading
Loading