ranges: compute LinRange elements as a + t*(b - a) #64388
Approved these changes.
This version can run into issues where b-a is poorly conditioned. Specifically, it can lead to results outside (a,b) which our current formula never does.
I'm not sure this version is uniformly better. I think it's a tradeoff.
I think that describes the current formula. It is the one that gives results outside [a, b], which is the bug this PR fixes (#64272):
julia> collect(LinRange(0.1, 0.1, 6))[2]
0.10000000000000002
julia> LinRange(0.9, nextfloat(0.9), 10)[2]
0.8999999999999999
This PR's version is monotonic. With a and b - a fixed, each rounding step in a + t(b - a) preserves order, so the elements move in one direction as t grows, and the last element is b exactly. When b - a overflows, which needs endpoints of opposite signs, it falls back to the current (1-t)a + t*b, and for opposite signs both terms of that move the same way, so it stays monotonic and inside [a, b].
I also tested random ranges. With endpoints 0 to 8 ulps apart, the current formula put an element outside [a, b] in 12,337 of 20,000 ranges. This PR put none outside in 940,000 ranges, including endpoints of either sign from 1e-20 to 1e20 and lengths up to 2^62. Do you have an input in mind where it does?
The one tradeoff I found is accuracy when |a| is much larger than |b|: the worst element error was 149 ulps, versus 41 for the current formula. Computing each element from the nearer endpoint, as PyTorch and Octave do, brought that back to 41 while keeping the guarantees above, so I can switch to that if you prefer.
Given how this example was found, maybe the test should be a Lean proof instead of checking an example? (If you want that done later, we could add a comment flagging it as something to replace with Lean later.)
Approved these changes.
doctest failed, need update:
┌ Error: doctest failure in range.jl:571-587
--
| │
| │ jldoctest| │ julia> collect(range(-0.1, 0.3, length=5))
| │ 5-element Vector{Float64}:
| │ -0.1
| │ 0.0
| │ 0.1
| │ 0.2
| │ 0.3
| │
| │ julia> collect(LinRange(-0.1, 0.3, 5))
| │ 5-element Vector{Float64}:
| │ -0.1
| │ -1.3877787807814457e-17
| │ 0.09999999999999999
| │ 0.19999999999999998
| │ 0.3
| │
| │
| │ Subexpression:
| │
| │ collect(LinRange(-0.1, 0.3, 5))
| │
| │ Evaluated output:
| │
| │ 5-element Vector{Float64}:
| │ -0.1
| │ 0.0
| │ 0.1
| │ 0.20000000000000004
| │ 0.3
| │
| │ Expected output:
| │
| │ 5-element Vector{Float64}:
| │ -0.1
| │ -1.3877787807814457e-17
| │ 0.09999999999999999
| │ 0.19999999999999998
| │ 0.3
| │
| │ diff =
| │ 5-element Vector{Float64}:
| │ -0.1
| │ -1.3877787807814457e-17
| │ 0.09999999999999999
| │ 0.19999999999999998
| │ -0.1
| │ 0.0
| │ 0.1
| │ 0.20000000000000004
| │ 0.3
| └ @ Documenter range.jl:571
Updated the documentation example to match the new interpolation output, and checked it against the actual branch output.
The x86_64-linux-gnuassert build failed while compiling lerpi, with "GlobalRef not allowed in value position" followed by "IR verification failed". I think the cause was the dot call in the previous version, T(_lerp.(j/d, a, b)): range.jl is loaded before broadcast.jl, so when the compiler is built, that call refers to broadcasting functions that don't exist yet.
The new push keeps the formula unchanged and only moves the bookkeeping: range.jl defines lerpi for T<:Number without broadcasting, and the broadcasting method for other endpoint types, such as arrays, is now defined in broadcast.jl. I loaded both methods into nightly and ran test/ranges.jl, which passes, but this hasn't been through a full build yet, so CI is the real check.
JeffBezanson
MilesCranmerBot
Fixes #64272
LinRangeelements can step backwards, leave the interval between the endpoints, or throw anInexactErrorfor integer ranges; they should be monotonic, lie betweenstartandstop, and be exact when the step is an integer.With this PR:
Cause:
lerpi(base/range.jl:992) computes(1-t)a + tb, rounding1-t, both products, and the sum separately, so the result is not monotonic intand(1-t)a + taneed not equala. The fix computesa + t(b - a), as NumPy, CuPy and Rust'sndarraydo (PyTorch and GNU Octave apply the same step from both ends), and returnsbexactly at the last index. Rounding preserves order, so the elements are monotonic and stay between the endpoints. Whereb - aoverflows, it keeps(1-t)a + t*b, which is monotonic for endpoints of opposite signs; C++20std::lerpmakes the same split. So unlike NumPy, whoselinspace(-m, m, 5)withm = floatmax()returns[nan, inf, inf, inf, m],LinRange(-floatmax(), floatmax(), 5)stays finite.Float16andFloat32still useFloat64arithmetic internally. The method stays generic and is broadcast over the endpoints, so vector endpoints get the same guarantees elementwise; Colors, Unitful, StaticArrays, GeometryBasics, ForwardDiff, Measurements, Quaternions, OffsetArrays andComplexendpoints were all explicitly checked to be compatible with this change. Adds tests intest/ranges.jl, and updates one test that compared vector-endpoint elements bit for bit with the old formula.Number ranges keep their speed and still vectorize; vector endpoints get faster, since the result is built in one pass:
|
@btime| before | after ||---|---|---|
|
r[i],Float64| 2.42 ns | 2.46 ns ||
collect(r),Float64, n=1000 | 417 ns | 416 ns ||
dest .= r,Float32, n=1000 | 398 ns | 398 ns ||
r[i], 100-element vector endpoints | 144 ns, 8 allocs | 84 ns, 4 allocs |Found while formalizing Base in Lean:
InexactErrorfor integer ranges: bug report, Lean proof