From 65a0b60cf617b949f2d5a23e0858291ae8188762 Mon Sep 17 00:00:00 2001 From: Nathan Date: Sun, 18 Oct 2026 12:18:52 -0400 Subject: [PATCH] Fix finite floating-point average overflow --- CMakeLists.txt | 3 +- docs/standard-library/floating-averages.md | 69 ++++++++++++ docs/standard-library/index.md | 4 + matrix/docs/next-version-findings.md | 30 +++-- nilstd/README.md | 5 + nilstd/src/core/sorting.ny | 83 +++++++++++++- scripts/check-sdk-routes.py | 1 + tests/language/average-f64-matrix.matrix | 122 +++++++++++++++++++++ tests/language/average-f64-matrix.stdout | 6 + tests/language/average-f64.ny | 117 ++++++++++++++++++++ tests/language/average-f64.stdout | 6 + 11 files changed, 437 insertions(+), 9 deletions(-) create mode 100644 docs/standard-library/floating-averages.md create mode 100644 tests/language/average-f64-matrix.matrix create mode 100644 tests/language/average-f64-matrix.stdout create mode 100644 tests/language/average-f64.ny create mode 100644 tests/language/average-f64.stdout diff --git a/CMakeLists.txt b/CMakeLists.txt index 33a5135d..b895a11b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2301,7 +2301,8 @@ if(BUILD_TESTING) foreach(parity_fixture IN ITEMS scientific-literals scientific-literals-matrix integer-literal-widths integer-literal-widths-matrix checked-text-spans checked-text-spans-matrix - checked-i64-conversion checked-i64-conversion-matrix) + checked-i64-conversion checked-i64-conversion-matrix + average-f64 average-f64-matrix) if(parity_fixture MATCHES "-matrix$") set(parity_frontend matrix) else() diff --git a/docs/standard-library/floating-averages.md b/docs/standard-library/floating-averages.md new file mode 100644 index 00000000..6e56f613 --- /dev/null +++ b/docs/standard-library/floating-averages.md @@ -0,0 +1,69 @@ +# Floating-point averages + +`average_f64(items: array) -> Option` is available from +`nil.std.core` in both Ny and Matrix. The legacy `ny.lang.core` import resolves +to the same implementation. + +| Input | Result | +| --- | --- | +| Empty array | `None`. | +| Nonempty array of finite values | `Some(mean)`, with a finite approximation to the arithmetic mean inside the input's minimum/maximum interval. | +| Any NaN or infinity | The original ordered `sum_f64(items) / count` computation, wrapped in `Some`. | + +The function leaves the input and its aliases unchanged. It takes O(n) time +and O(1) auxiliary storage. `sum_f64` retains its existing ordered, uncompensated +addition behavior, including intermediate overflow. + +```ny +import nil.std.core + +fn main() -> i32 + let mean = average_f64([1e308, 1e308]).unwrap() + println(mean == 1e308) + return 0 +end fn +``` + +```matrix +book examples.floating-averages + +read everything from nil.std.core + +main returns override integer begin paragraph + value mean is (average-f64 with arr being [1e308, 1e308]).unwrap with nothing + say mean equals 1e308 + give 0 +end paragraph +``` + +The previous implementation overflowed while summing the two values in these +examples. The updated implementation keeps two compensated subtotals: values +of magnitude at most one remain unscaled, while larger values are divided by +a power of two greater than the array length. This leaves headroom for the +large subtotal without underflowing the small inputs. The final merge retains +addition residuals and restores the original scale when cancellation makes +that safe. A final range clamp prevents rounding from escaping the input +interval, including at the largest finite value. + +The correction uses a magnitude-ordered addition residual, as described in +[Ogita, Rump and Oishi, *Accurate Sum and Dot Product*, section 1.1](https://www.tuhh.de/ti3/paper/rump/OgRuOi05.pdf). +This implementation does not provide an exact accumulator, guaranteed correct +rounding, a universal ULP bound, or order-independent results. Severe +cancellation can still erase a representable residual: for example, +`[1e100, 1e308, 1.7976931348623157e308, -1e308, -1.7976931348623157e308]` +can produce zero instead of a value near `2e99`. That accuracy limit remains +follow-up work. Values close to zero can also round to zero normally. + +For nonfinite inputs, retaining ordered summation is deliberate. A NaN +propagates; opposite infinities produce NaN. Intermediate finite overflow can +also affect the result: `[1e308, 1e308, -infinity]` still produces NaN after +the first two terms overflow. This compatibility path does not use the finite +averaging algorithm. + +Paired Ny and Matrix fixtures cover ordinary means, extreme magnitudes, +cancellation, subnormal values and rounding ties, empty arrays, signed zeros, +nonfinite inputs and source preservation. Finite reference values are derived +from exact rational sums of the binary64 inputs. These fixtures run through +the textual/binary interpreter, bundles, LLVM JIT/AOT, standalone +assembler/linker pipelines, and installed source/binary libraries. Their +individual tolerances establish the tested cases, not a general error bound. diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index 6788efe8..ec5b7bbe 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -20,6 +20,8 @@ The [checked text-span reference](text-spans.md) defines exact byte ranges, empty-span results, and overflow-safe compatibility slicing. The [checked integer-conversion reference](integer-conversion.md) covers decimal parsing and matching `Result` behavior on VM and native routes. +The [floating-average reference](floating-averages.md) defines bounded finite +averaging, nonfinite compatibility behavior and numerical accuracy limits. ```text nilstd/ @@ -309,6 +311,8 @@ This changes the older library behavior around NaNs. It does not change the language's IEEE operators: NaN remains unequal to itself under `==`, and ordinary ordered comparisons with NaN remain false. `sum_f64` and `average_f64` continue to propagate NaN through ordinary arithmetic. +For finite inputs, `average_f64` uses compensated subtotals to avoid sum +overflow; see the [averaging contract](floating-averages.md) for accuracy limits. Sorting preserves the original relative order of signed zeros and NaNs. The explicitly named insertion sorts remain O(n²). `merge_sort_i32` retains diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 1a574c13..7e809932 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1020,9 +1020,9 @@ pattern binding directly; no grammar change was made in this pass. ### F32 — Floating averages can overflow for finite inputs -**Status:** Confirmed open numerical bug. +**Status:** Fixed for finite-input overflow; severe-cancellation accuracy remains limited. -`average_f64` currently computes `sum_f64(items) / count`. For +`average_f64` previously computed `sum_f64(items) / count`. For `[1e308, 1e308]`, the intermediate sum overflows to positive infinity although the mean `1e308` is representable. Negative inputs behave symmetrically, and `[1e308, 1e308, -1e308]` also produces positive infinity instead of a finite @@ -1030,11 +1030,27 @@ mean. Paired Ny/Matrix probes reproduce these results on all six routes; sources and reports are under `build/text-core-work/average-overflow` in the v1 library checkout. -**Next step:** Implement a bounded finite-input averaging algorithm without -changing `sum_f64` or the existing empty/NaN/infinity contracts. Qualify extreme -magnitudes, cancellation, subnormals and ordinary rounding against independent -numerical oracles. Scaling the inputs is a candidate, but its loss of very -small terms under severe cancellation needs explicit consideration. +**Resolution:** Accumulate two compensated subtotals. Values of magnitude at +most one retain their scale so subnormal terms survive; larger values use an +exact power-of-two divisor greater than the count, leaving overflow headroom. +Retain the rounding tail when merging the subtotals, restore the original +scale when safe, and clamp the result to the input interval. `sum_f64` is +unchanged. Empty inputs still return `None`; any nonfinite input deliberately +uses the original ordered sum/division path, including its order dependence. + +**Verification:** Paired Ny/Matrix fixtures cover finite extremes, repeated +maximum values, cancellation across both subtotals, subnormal ties, aliases +and nonfinite compatibility on all execution routes and installed libraries. +Finite expectations come from exact rational arithmetic on the binary64 +inputs. The [averaging contract](../../docs/standard-library/floating-averages.md) +records the algorithm and evidence boundary. + +**Remaining numerical limitation:** Compensation is not exact accumulation. +For `[1e100, 1e308, 1.7976931348623157e308, -1e308, -1.7976931348623157e308]`, +the small residual can still disappear, yielding zero instead of a mean near +`2e99`. Do not promise correct rounding, universal ULP accuracy or permutation +invariance. An exact or expanded accumulator is separate future work. There +is no new public API or compiler intrinsic in this fix. ### F33 — Native iteration over an array literal selects an absent iterator diff --git a/nilstd/README.md b/nilstd/README.md index f05979e6..7c30110b 100644 --- a/nilstd/README.md +++ b/nilstd/README.md @@ -52,6 +52,11 @@ below. ### Active evidence boundary +Finite `average_f64` inputs use compensated subtotals to avoid intermediate +sum overflow. Paired Ny/Matrix fixtures cover the VM and native paths; the +[floating-average contract](../docs/standard-library/floating-averages.md) +describes nonfinite compatibility behavior and the remaining accuracy limits. + Checked text access (`try_substring`, `try_char_at`) and checked decimal `Convert.try_to_i64` parsing have paired Ny/Matrix VM/native fixtures. See the [text-span contract](../docs/standard-library/text-spans.md) and diff --git a/nilstd/src/core/sorting.ny b/nilstd/src/core/sorting.ny index 9153bf50..50c5d452 100644 --- a/nilstd/src/core/sorting.ny +++ b/nilstd/src/core/sorting.ny @@ -443,12 +443,93 @@ pub fn sum_f64(arr: array) -> f64 return total end fn +# Recover the addition roundoff by subtracting the larger operand first. +# Callers keep the operands and their sum finite; reassociation is unsafe. +fn average_f64_roundoff(left: f64, right: f64, total: f64) -> f64 + let mut left_size = left + let mut right_size = right + if left_size < 0.0 then left_size = -left_size end if + if right_size < 0.0 then right_size = -right_size end if + if left_size >= right_size then + return (left - total) + right + end if + return (right - total) + left +end fn + +# Merge the two subtotals and their corrections without allocating an array. +fn average_f64_merge(a: f64, b: f64, c: f64, d: f64) -> f64 + let first = a + b + let mut error = average_f64_roundoff(a, b, first) + let second = first + c + error = error + average_f64_roundoff(first, c, second) + let third = second + d + error = error + average_f64_roundoff(second, d, third) + return third + error +end fn + +# A finite mean must not overflow merely because its unscaled sum does. +# Compensate two sums: values of magnitude <= 1 stay unscaled, preserving +# subnormals, while larger values use an exact power-of-two divisor > count. +# This is an approximation, not an exact or correctly rounded reduction. pub fn average_f64(arr: array) -> Option let n = arr.length() if n == 0 then return Option.None end if - return Option.Some(sum_f64(arr) / (n as f64)) + let count = n as f64 + let mut scale: f64 = 1.0 + while scale < count do + scale = scale * 2.0 + end while + scale = scale * 2.0 + + let mut large: f64 = 0.0 + let mut large_error: f64 = 0.0 + let mut small: f64 = 0.0 + let mut small_error: f64 = 0.0 + let mut lower = arr[0] + let mut upper = arr[0] + let mut i = 0 + while i < n do + let item = arr[i] + if item != item or (item - item) != 0.0 then + # Retain the original ordered IEEE arithmetic for nonfinite input. + return Option.Some(sum_f64(arr) / count) + end if + if item < lower then lower = item end if + if item > upper then upper = item end if + if item >= -1.0 and item <= 1.0 then + let next = small + item + small_error = small_error + average_f64_roundoff(small, item, next) + small = next + else + let scaled = item / scale + let next = large + scaled + large_error = large_error + average_f64_roundoff(large, scaled, next) + large = next + end if + i = i + 1 + end while + + let large_total = large + large_error + let large_tail = average_f64_roundoff(large, large_error, large_total) + let mut mean: f64 = 0.0 + if large_total >= -1.0 and large_total <= 1.0 then + # Cancellation made the large subtotal safe to restore. Merge before + # dividing so tiny residuals and subnormal ties survive the reduction. + let restored = large_total * scale + let restored_tail = large_tail * scale + mean = average_f64_merge(restored, small, restored_tail, small_error) / count + else + # The large subtotal dominates the small group, whose magnitude is at + # most count / scale <= 1/2. Keep this merge scaled to avoid overflow. + let combined = average_f64_merge(large_total, small / scale, large_tail, small_error / scale) + mean = combined / (count / scale) + end if + # Rounding at the largest finite value must not escape the input range. + if mean < lower then mean = lower end if + if mean > upper then mean = upper end if + return Option.Some(mean) end fn # ============================================================================= diff --git a/scripts/check-sdk-routes.py b/scripts/check-sdk-routes.py index 10751148..78651dcd 100644 --- a/scripts/check-sdk-routes.py +++ b/scripts/check-sdk-routes.py @@ -45,6 +45,7 @@ "integer-literal-widths", "integer-literal-widths-matrix", "checked-text-spans", "checked-text-spans-matrix", "checked-i64-conversion", "checked-i64-conversion-matrix", + "average-f64", "average-f64-matrix", "random-generators", "random-generators-matrix", "math-runtime") diff --git a/tests/language/average-f64-matrix.matrix b/tests/language/average-f64-matrix.matrix new file mode 100644 index 00000000..49255cc4 --- /dev/null +++ b/tests/language/average-f64-matrix.matrix @@ -0,0 +1,122 @@ +book validation.average-f64 +read everything from ny.lang.core +read everything from ny.lang.math + +require receives ok as boolean, label as text returns nothing begin paragraph + when not ok then evaluate panic with label end when +end paragraph + +!!! Oracles are nearest binary64 values of exact Fraction sums of the binary64 +!!! inputs divided by count. Nonzero tolerances below are four oracle ULPs; +!!! zero tolerances deliberately cover exact results and subnormal rounding. +near receives items as array of floating, expected as floating, tolerance as floating, label as text returns nothing begin paragraph + value result is average-f64 with arr being items + evaluate require with ok being (result.is-some with nothing), label being label + value actual is result.unwrap with nothing + evaluate require with ok being (is-finite with actual), label being label + variable lower is items at 0 + variable upper is items at 0 + repeat for index from 0 to (the length of items) + when (items at index) is less than lower then set lower to (items at index) end when + when (items at index) is greater than upper then set upper to (items at index) end when + end repeat + evaluate require with ok being (actual is at least lower and actual is at most upper), label being label + evaluate require with ok being ((abs with (actual minus expected)) is at most tolerance), label being label +end paragraph + +nan-mean receives items as array of floating, label as text returns nothing begin paragraph + value result is average-f64 with arr being items + evaluate require with ok being (result.is-some with nothing), label being label + value actual is result.unwrap with nothing + evaluate require with ok being (actual does not equal actual), label being label +end paragraph + +infinite-mean receives items as array of floating, expected as floating, label as text returns nothing begin paragraph + value result is average-f64 with arr being items + evaluate require with ok being (result.is-some with nothing), label being label + value actual is result.unwrap with nothing + evaluate require with ok being (actual equals expected), label being label +end paragraph + +main returns override integer begin paragraph + value empty-mean is average-f64 with arr being [] + evaluate require with ok being (empty-mean.is-none with nothing), label being "empty mean is absent" + evaluate near with items being [2.0, 4.0, 6.0], expected being 4.0, tolerance being 0.0, label being "ordinary exact mean" + evaluate near with items being [0.1, 0.2, 0.3], expected being 0.2, tolerance being 1.1102230246251565e-16, label being "fractional mean" + evaluate near with items being [minus 3.0, 0.0, 3.0], expected being 0.0, tolerance being 0.0, label being "ordinary cancellation" + evaluate near with items being [0.0, minus 0.0], expected being 0.0, tolerance being 0.0, label being "zero mean" + value zero-mean is average-f64 with arr being [minus 0.0, minus 0.0] + evaluate require with ok being ((atan2 with y being (zero-mean.unwrap with nothing), x being minus 1.0) is greater than 0.0), label being "negative-zero mean retains positive zero" + value original is [2.0, minus 0.0, 8.0] + value alias is original + evaluate near with items being original, expected being 3.3333333333333335, tolerance being 1.7763568394002505e-15, label being "input alias mean" + evaluate require with ok being ((the length of alias) equals 3 and (alias at 0) equals 2.0 and (alias at 2) equals 8.0), label being "input values preserved" + evaluate require with ok being ((atan2 with y being (alias at 1), x being minus 1.0) is less than 0.0), label being "input negative zero preserved" + say "ordinary means and source aliases" + + value maximum is 1.7976931348623157e308 + evaluate near with items being [maximum], expected being maximum, tolerance being 0.0, label being "maximum singleton" + evaluate near with items being [minus maximum], expected being minus maximum, tolerance being 0.0, label being "minimum singleton" + evaluate near with items being [1e308, 1e308], expected being 1e308, tolerance being 7.98336123813888e292, label being "positive intermediate overflow" + evaluate near with items being [minus 1e308, minus 1e308], expected being minus 1e308, tolerance being 7.98336123813888e292, label being "negative intermediate overflow" + evaluate near with items being [maximum, maximum, maximum], expected being maximum, tolerance being 7.98336123813888e292, label being "maximum repeated" + evaluate near with items being [maximum, maximum, maximum, maximum, maximum], expected being maximum, tolerance being 0.0, label being "constant maximum endpoint" + evaluate near with items being [minus maximum, minus maximum, minus maximum], expected being minus maximum, tolerance being 7.98336123813888e292, label being "minimum repeated" + evaluate near with items being [1e308, 1e308, minus 1e308], expected being 3.333333333333333e307, tolerance being 1.99584030953472e292, label being "positive mixed overflow" + evaluate near with items being [1e308, minus 1e308, 1e308], expected being 3.333333333333333e307, tolerance being 1.99584030953472e292, label being "mixed permutation" + evaluate near with items being [minus 1e308, minus 1e308, 1e308], expected being minus 3.333333333333333e307, tolerance being 1.99584030953472e292, label being "negative mixed overflow" + evaluate near with items being [1e308, 1e308, minus 1e308, minus 1e308], expected being 0.0, tolerance being 0.0, label being "balanced overflowing groups" + evaluate near with items being [maximum, minus maximum], expected being 0.0, tolerance being 0.0, label being "opposite maxima" + say "finite overflow and mixed signs" + + evaluate near with items being [1e16, 1.0, minus 1e16], expected being 0.3333333333333333, tolerance being 2.220446049250313e-16, label being "moderate cancellation residue" + evaluate near with items being [1e16, 1.0, 1.0, minus 1e16], expected being 0.5, tolerance being 0.0, label being "two cancellation units" + evaluate near with items being [3.0, 1.0000000000000002, minus 2.0, minus 1.0, minus 1.0], expected being 4.4408920985006264e-17, tolerance being 2.465190328815662e-32, label being "compensation tail before small terms" + evaluate near with items being [2.0000000000000004, 1.9999999999999998, minus 1.0, minus 1.0, minus 1.0, minus 1.0], expected being 3.700743415417188e-17, tolerance being 2.465190328815662e-32, label being "opposite compensation tails" + evaluate near with items being [minus 1.0, 2.0000000000000004, minus 1.0, 1.9999999999999998, minus 1.0, minus 1.0], expected being 3.700743415417188e-17, tolerance being 2.465190328815662e-32, label being "compensation tail permutation" + evaluate near with items being [minus 2.0000000000000004, minus 1.9999999999999998, 1.0, 1.0, 1.0, 1.0], expected being minus 3.700743415417188e-17, tolerance being 2.465190328815662e-32, label being "negative compensation tails" + evaluate near with items being [1e308, 1.0, minus 1e308], expected being 0.3333333333333333, tolerance being 2.220446049250313e-16, label being "extreme cancellation residue" + evaluate near with items being [1e308, 1e308, minus 1e308, minus 1e308, 3e-300], expected being 6.000000000000001e-301, tolerance being 3.3156184e-316, label being "tiny residue after overflow" + evaluate near with items being [3e-300, minus 1e308, 1e308, minus 1e308, 1e308], expected being 6.000000000000001e-301, tolerance being 3.3156184e-316, label being "tiny residue permutation" + evaluate near with items being [1e308, 1e-308, minus 1e308], expected being 3.33333333333333e-309, tolerance being 2e-323, label being "subnormal cancellation residue" + evaluate near with items being [maximum, minus maximum, 2.2250738585072014e-308], expected being 7.41691286169067e-309, tolerance being 2e-323, label being "minimum normal residue" + evaluate near with items being [1e308, 1e308, minus 1e308, minus 1e308, 5e-324], expected being 0.0, tolerance being 0.0, label being "unrepresentable final residue rounds to zero" + say "compensated cancellation" + + value tiny is 5e-324 + evaluate near with items being [tiny, tiny], expected being tiny, tolerance being 0.0, label being "repeated minimum subnormal" + evaluate near with items being [minus tiny, minus tiny], expected being minus tiny, tolerance being 0.0, label being "negative minimum subnormal" + evaluate near with items being [tiny, 0.0, tiny], expected being tiny, tolerance being 0.0, label being "subnormal thirds" + evaluate near with items being [tiny, 0.0], expected being 0.0, tolerance being 0.0, label being "subnormal tie rounds to even zero" + evaluate near with items being [1.5e-323, 0.0], expected being 1e-323, tolerance being 0.0, label being "subnormal tie rounds to even nonzero" + evaluate near with items being [tiny, 1e-323, 1.5e-323], expected being 1e-323, tolerance being 0.0, label being "mixed subnormal mean" + evaluate near with items being [2.2250738585072014e-308, 2.2250738585072014e-308, 2.2250738585072014e-308], expected being 2.2250738585072014e-308, tolerance being 0.0, label being "minimum normal repeated" + evaluate near with items being [2.2250738585072014e-308, 2.225073858507201e-308], expected being 2.2250738585072014e-308, tolerance being 0.0, label being "normal boundary tie" + say "subnormal means and rounding" + + variable large-values as array of floating is [] + variable small-values as array of floating is [] + repeat for index from 0 to 257 + append maximum to large-values + append tiny to small-values + end repeat + evaluate near with items being large-values, expected being maximum, tolerance being 7.98336123813888e292, label being "257 maximum values" + evaluate near with items being small-values, expected being tiny, tolerance being 0.0, label being "257 minimum subnormals" + say "repeated maximum and subnormal means" + + value infinity is exp with 1000.0 + value nan is sqrt with minus 1.0 + evaluate infinite-mean with items being [infinity], expected being infinity, label being "positive infinity singleton" + evaluate infinite-mean with items being [minus infinity], expected being minus infinity, label being "negative infinity singleton" + evaluate infinite-mean with items being [infinity, 1e308, 1e308], expected being infinity, label being "positive infinity propagates" + evaluate infinite-mean with items being [minus infinity, 1e308, 1e308], expected being minus infinity, label being "negative infinity precedes large terms" + evaluate nan-mean with items being [nan], label being "NaN singleton" + evaluate nan-mean with items being [1.0, nan, 2.0], label being "NaN inside input" + evaluate nan-mean with items being [infinity, minus infinity], label being "opposite infinities" + evaluate nan-mean with items being [infinity, nan, minus infinity], label being "NaN and infinities" + evaluate nan-mean with items being [1e308, 1e308, minus infinity], label being "historical overflow before opposite infinity" + evaluate nan-mean with items being [minus 1e308, minus 1e308, infinity], label being "historical negative overflow before infinity" + evaluate require with ok being ((sum-f64 with arr being [1e308, 1e308]) equals infinity), label being "sum retains ordinary overflowing arithmetic" + say "nonfinite input contracts" + give 0 +end paragraph diff --git a/tests/language/average-f64-matrix.stdout b/tests/language/average-f64-matrix.stdout new file mode 100644 index 00000000..ff124b0b --- /dev/null +++ b/tests/language/average-f64-matrix.stdout @@ -0,0 +1,6 @@ +ordinary means and source aliases +finite overflow and mixed signs +compensated cancellation +subnormal means and rounding +repeated maximum and subnormal means +nonfinite input contracts diff --git a/tests/language/average-f64.ny b/tests/language/average-f64.ny new file mode 100644 index 00000000..9755c9fa --- /dev/null +++ b/tests/language/average-f64.ny @@ -0,0 +1,117 @@ +import nil.std.core +import nil.std.math + +fn require(ok: bool, label: text) + if not ok then panic(label) end if +end fn + +# Oracles are nearest binary64 values of exact Fraction sums of the binary64 +# inputs divided by count. Nonzero tolerances below are four oracle ULPs; +# zero tolerances deliberately cover exact results and subnormal rounding. +fn near(items: array, expected: f64, tolerance: f64, label: text) + let result = average_f64(items) + require(result.is_some(), label) + let actual = result.unwrap() + require(is_finite(actual), label) + let mut lower = items[0] + let mut upper = items[0] + for index in range(items.len()) + if items[index] < lower then lower = items[index] end if + if items[index] > upper then upper = items[index] end if + end for + require(actual >= lower and actual <= upper, label) + require(abs(actual - expected) <= tolerance, label) +end fn + +fn nan_mean(items: array, label: text) + let result = average_f64(items) + require(result.is_some(), label) + let actual = result.unwrap() + require(actual != actual, label) +end fn + +fn infinite_mean(items: array, expected: f64, label: text) + let result = average_f64(items) + require(result.is_some() and result.unwrap() == expected, label) +end fn + +fn main() -> i32 + require(average_f64([]).is_none(), "empty mean is absent") + near([2.0, 4.0, 6.0], 4.0, 0.0, "ordinary exact mean") + near([0.1, 0.2, 0.3], 0.2, 1.1102230246251565e-16, "fractional mean") + near([-3.0, 0.0, 3.0], 0.0, 0.0, "ordinary cancellation") + near([0.0, -0.0], 0.0, 0.0, "zero mean") + require(atan2(average_f64([-0.0, -0.0]).unwrap(), -1.0) > 0.0, "negative-zero mean retains positive zero") + let original = [2.0, -0.0, 8.0] + let alias = original + near(original, 3.3333333333333335, 1.7763568394002505e-15, "input alias mean") + require(alias.len() == 3 and alias[0] == 2.0 and alias[2] == 8.0, "input values preserved") + require(atan2(alias[1], -1.0) < 0.0, "input negative zero preserved") + println("ordinary means and source aliases") + + let maximum = 1.7976931348623157e308 + near([maximum], maximum, 0.0, "maximum singleton") + near([-maximum], -maximum, 0.0, "minimum singleton") + near([1e308, 1e308], 1e308, 7.98336123813888e292, "positive intermediate overflow") + near([-1e308, -1e308], -1e308, 7.98336123813888e292, "negative intermediate overflow") + near([maximum, maximum, maximum], maximum, 7.98336123813888e292, "maximum repeated") + near([maximum, maximum, maximum, maximum, maximum], maximum, 0.0, "constant maximum endpoint") + near([-maximum, -maximum, -maximum], -maximum, 7.98336123813888e292, "minimum repeated") + near([1e308, 1e308, -1e308], 3.333333333333333e307, 1.99584030953472e292, "positive mixed overflow") + near([1e308, -1e308, 1e308], 3.333333333333333e307, 1.99584030953472e292, "mixed permutation") + near([-1e308, -1e308, 1e308], -3.333333333333333e307, 1.99584030953472e292, "negative mixed overflow") + near([1e308, 1e308, -1e308, -1e308], 0.0, 0.0, "balanced overflowing groups") + near([maximum, -maximum], 0.0, 0.0, "opposite maxima") + println("finite overflow and mixed signs") + + near([1e16, 1.0, -1e16], 0.3333333333333333, 2.220446049250313e-16, "moderate cancellation residue") + near([1e16, 1.0, 1.0, -1e16], 0.5, 0.0, "two cancellation units") + near([3.0, 1.0000000000000002, -2.0, -1.0, -1.0], 4.4408920985006264e-17, 2.465190328815662e-32, "compensation tail before small terms") + near([2.0000000000000004, 1.9999999999999998, -1.0, -1.0, -1.0, -1.0], 3.700743415417188e-17, 2.465190328815662e-32, "opposite compensation tails") + near([-1.0, 2.0000000000000004, -1.0, 1.9999999999999998, -1.0, -1.0], 3.700743415417188e-17, 2.465190328815662e-32, "compensation tail permutation") + near([-2.0000000000000004, -1.9999999999999998, 1.0, 1.0, 1.0, 1.0], -3.700743415417188e-17, 2.465190328815662e-32, "negative compensation tails") + near([1e308, 1.0, -1e308], 0.3333333333333333, 2.220446049250313e-16, "extreme cancellation residue") + near([1e308, 1e308, -1e308, -1e308, 3e-300], 6.000000000000001e-301, 3.3156184e-316, "tiny residue after overflow") + near([3e-300, -1e308, 1e308, -1e308, 1e308], 6.000000000000001e-301, 3.3156184e-316, "tiny residue permutation") + near([1e308, 1e-308, -1e308], 3.33333333333333e-309, 2e-323, "subnormal cancellation residue") + near([maximum, -maximum, 2.2250738585072014e-308], 7.41691286169067e-309, 2e-323, "minimum normal residue") + near([1e308, 1e308, -1e308, -1e308, 5e-324], 0.0, 0.0, "unrepresentable final residue rounds to zero") + println("compensated cancellation") + + let tiny = 5e-324 + near([tiny, tiny], tiny, 0.0, "repeated minimum subnormal") + near([-tiny, -tiny], -tiny, 0.0, "negative minimum subnormal") + near([tiny, 0.0, tiny], tiny, 0.0, "subnormal thirds") + near([tiny, 0.0], 0.0, 0.0, "subnormal tie rounds to even zero") + near([1.5e-323, 0.0], 1e-323, 0.0, "subnormal tie rounds to even nonzero") + near([tiny, 1e-323, 1.5e-323], 1e-323, 0.0, "mixed subnormal mean") + near([2.2250738585072014e-308, 2.2250738585072014e-308, 2.2250738585072014e-308], 2.2250738585072014e-308, 0.0, "minimum normal repeated") + near([2.2250738585072014e-308, 2.225073858507201e-308], 2.2250738585072014e-308, 0.0, "normal boundary tie") + println("subnormal means and rounding") + + let mut large_values: array = [] + let mut small_values: array = [] + for index in range(257) + large_values.push(maximum) + small_values.push(tiny) + end for + near(large_values, maximum, 7.98336123813888e292, "257 maximum values") + near(small_values, tiny, 0.0, "257 minimum subnormals") + println("repeated maximum and subnormal means") + + let infinity = exp(1000.0) + let nan = sqrt(-1.0) + infinite_mean([infinity], infinity, "positive infinity singleton") + infinite_mean([-infinity], -infinity, "negative infinity singleton") + infinite_mean([infinity, 1e308, 1e308], infinity, "positive infinity propagates") + infinite_mean([-infinity, 1e308, 1e308], -infinity, "negative infinity precedes large terms") + nan_mean([nan], "NaN singleton") + nan_mean([1.0, nan, 2.0], "NaN inside input") + nan_mean([infinity, -infinity], "opposite infinities") + nan_mean([infinity, nan, -infinity], "NaN and infinities") + nan_mean([1e308, 1e308, -infinity], "historical overflow before opposite infinity") + nan_mean([-1e308, -1e308, infinity], "historical negative overflow before infinity") + require(sum_f64([1e308, 1e308]) == infinity, "sum retains ordinary overflowing arithmetic") + println("nonfinite input contracts") + return 0 +end fn diff --git a/tests/language/average-f64.stdout b/tests/language/average-f64.stdout new file mode 100644 index 00000000..ff124b0b --- /dev/null +++ b/tests/language/average-f64.stdout @@ -0,0 +1,6 @@ +ordinary means and source aliases +finite overflow and mixed signs +compensated cancellation +subnormal means and rounding +repeated maximum and subnormal means +nonfinite input contracts