`var(::AbstractRange)` overflows in the closed form: negative variance for narrow integer ranges and for long `Int64` ranges

Open Beginner friendly
#219 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
74/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Domain
data

Research direction

Start from the varm method for AbstractRange and from range_varm, which the issue names, in the Statistics source. Reproduce with var(Int8(-1):Int8(126):Int8(127)) and compare against var(collect(...)). Done means the closed form converts step, offset and length to float before multiplying, and both range cases return correct values, checked by tests for narrow and long integer ranges.

Written by the indexing model from the issue text.

Description

julia> using Statistics

julia> r = Int8(-1):Int8(126):Int8(127);

julia> var(r), var(collect(r))
(-7934.0, 7938.0)

julia> std(r)
ERROR: DomainError with -7934.0:
sqrt was called with a negative real argument ...

julia> var(1:3_000_000_000)
-2.3244573453682586e18      # exact: 7.5e17

varm(v::AbstractRange, m; corrected) uses the closed form
abs2(s) * (l + 1) * l / 12 with s = step(v) and l = length(v).
abs2(s) is evaluated in the element type, so abs2(Int8(126)) wraps, and
(l + 1) * l is an Int product that overflows once the length exceeds
about 3.04e9. The same two problems exist in range_varm (abs2(f),
abs2(s), l * (2 * l - 1)), which is used when a mean is supplied.

This is the var counterpart of #120, where mean of integer ranges was
computed in the element type; converting s, f and l to float first,
as mean(::AbstractRange) now does, would fix both.

Reproduces for Int8, UInt8, Int16 and Int64 ranges on Statistics
1.11.5 with Julia 1.13.3 and nightly 1.15.0-DEV.720. Searches for var range, var overflow, std range and varm range found no matching issue
or PR (2026-11-13).

Assisted-by: AI

Dominant language
Julia
Stars
93
Forks
51
PR merge metrics
No merged PRs in 30d

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from JuliaStats/Statistics.jl

All issues in JuliaStats/Statistics.jl

Similar issues

More Julia issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.