← Back to Pull requests

ranges: compute LinRange elements as a + t*(b - a) #64388

Merged
MilesCranmerBot merged 3 files (35 lines) on Nov 02, 2026 01:26 UTC
View on GitHub
MilesCranmerBot MilesCranmerBot commented on Oct 28, 2026 01:34 UTC
Author

Fixes #64272

LinRange elements can step backwards, leave the interval between the endpoints, or throw an InexactError for integer ranges; they should be monotonic, lie between start and stop, and be exact when the step is an integer.

julia> collect(LinRange(0.9, nextfloat(0.9), 10))
10-element Vector{Float64}:
 0.9
 0.8999999999999999
 0.9000000000000001
 0.9000000000000001
 0.9
 0.9000000000000001
 0.9000000000000001
 0.9
 0.9000000000000001
 0.9000000000000001

julia> LinRange(-90:60:90)[2]
ERROR: InexactError: Int64(-30.000000000000007)

With this PR:

julia> collect(LinRange(0.9, nextfloat(0.9), 10))
10-element Vector{Float64}:
 0.9
 0.9
 0.9
 0.9
 0.9
 0.9000000000000001
 0.9000000000000001
 0.9000000000000001
 0.9000000000000001
 0.9000000000000001

julia> LinRange(-90:60:90)[2]
-30

Cause: lerpi (base/range.jl:992) computes (1-t)a + tb, rounding 1-t, both products, and the sum separately, so the result is not monotonic in t and (1-t)a + ta need not equal a. The fix computes a + t(b - a), as NumPy, CuPy and Rust's ndarray do (PyTorch and GNU Octave apply the same step from both ends), and returns b exactly at the last index. Rounding preserves order, so the elements are monotonic and stay between the endpoints. Where b - a overflows, it keeps (1-t)a + t*b, which is monotonic for endpoints of opposite signs; C++20 std::lerp makes the same split. So unlike NumPy, whose linspace(-m, m, 5) with m = floatmax() returns [nan, inf, inf, inf, m], LinRange(-floatmax(), floatmax(), 5) stays finite. Float16 and Float32 still use Float64 arithmetic 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 and Complex endpoints were all explicitly checked to be compatible with this change. Adds tests in test/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:

  • elements outside the endpoints: bug report, Lean proof

  • nonmonotonic elements: bug report, Lean proof

  • InexactError for integer ranges: bug report, Lean proof
  • Diff: 35 lines (+27 / -8) across 3 files Reviewer: JeffBezanson Review duration: 7192m
    All Vouch review confidence checks passed
    Residual risk 0.10 = Change Risk (0.27) × (1 − Review Confidence (0.65)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.27 · 35 lines diff across 3 files
    0.27
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.43 · 5 substantive comment(s)
    0.43
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    65%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.214
    Real PR Conversation Timeline
    10 items
    JeffBezanson JeffBezanson approved these changes on Oct 29, 2026 20:35 UTC
    Approved Reviewer

    Approved these changes.

    oscardssmith oscardssmith commented on Oct 29, 2026 20:40 UTC
    Contributor

    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.

    oscardssmith oscardssmith requested changes on Oct 29, 2026 20:40 UTC
    Changes Requested Reviewer

    I'm not sure this version is uniformly better. I think it's a tradeoff.

    MilesCranmerBot MilesCranmerBot commented on Oct 30, 2026 00:04 UTC
    Author

    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.

    ParadaCarleton ParadaCarleton commented on Oct 30, 2026 20:23 UTC
    Contributor

    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.)

    oscardssmith oscardssmith approved these changes on Oct 30, 2026 21:28 UTC
    Approved Reviewer

    Approved these changes.

    inkydragon inkydragon commented on Nov 01, 2026 15:30 UTC
    Contributor

    doctest failed, need update:

    https://buildkite.com/julialang/julia-pr/builds/5121/list?sid=01a195d2-349d-420e-af75-08e67a398e55&tab=output#01a195d2-34fb-43d0-a642-36ac98c644c5/L1181

    ┌ 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
    

    MilesCranmerBot MilesCranmerBot commented on Nov 01, 2026 16:41 UTC
    Author

    Updated the documentation example to match the new interpolation output, and checked it against the actual branch output.

    MilesCranmerBot MilesCranmerBot commented on Nov 01, 2026 19:02 UTC
    Author

    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.

    Reviewers
    Assignees
    MilesCranmerBot MilesCranmerBot
    Labels
    risk: low confidence: 65.1% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 27.4% (LOW) · Higher = larger blast radius
    27.4%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 65.1% · Lower = rushed or shallow review
    65.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 9.5% · Safe to merge
    9.5%