Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
69 changes: 69 additions & 0 deletions docs/standard-library/floating-averages.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Floating-point averages

`average_f64(items: array<f64>) -> Option<f64>` 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.
4 changes: 4 additions & 0 deletions docs/standard-library/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/
Expand Down Expand Up @@ -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
Expand Down
30 changes: 23 additions & 7 deletions matrix/docs/next-version-findings.md
Original file line number Diff line number Diff line change
Expand Up @@ -1020,21 +1020,37 @@ 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
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

Expand Down
5 changes: 5 additions & 0 deletions nilstd/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
83 changes: 82 additions & 1 deletion nilstd/src/core/sorting.ny
Original file line number Diff line number Diff line change
Expand Up @@ -443,12 +443,93 @@ pub fn sum_f64(arr: array<f64>) -> 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<f64>) -> Option<f64>
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

# =============================================================================
Expand Down
1 change: 1 addition & 0 deletions scripts/check-sdk-routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")


Expand Down
Loading
Loading