quantile(v, p; sorted=true) is O(n) due to unconditional NaN scan

Open
#203 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
68/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Quiet
Tech stack
julia
Domain
performance

Research direction

Start in src/Statistics.jl:1038 at _quantilesort!, then read the quantile docstring and test/runtests.jl:707-713. Compare the two proposed sorted-input behaviors and run the existing quantile tests plus the benchmark shown in the issue. Done means the selected behavior is documented by tests and sorted inputs no longer incur an unconditional O(n) scan.

Written by the indexing model from the issue text.

Description

quantile(v, p; sorted=true) scales linearly in length(v) despite the sort being skipped.

using Chairmarks, Statistics
for n in (10_000, 100_000, 1_000_000)
    v = sort(rand(n))
    @info "n=$n" (@b quantile($v, 0.25; sorted=true))
end
# n=10000     2.9 μs
# n=100000   28.5 μs
# n=1000000  300  μs   ≈ time of any(isnan, v) alone

Cause — _quantilesort! (src/Statistics.jl:1038):

if (sorted && (ismissing(v[end]) || (v[end] isa Number && isnan(v[end])))) ||
    any(x -> ismissing(x) || (x isa Number && isnan(x)), v)
    throw(ArgumentError(...))
end

Shape (sorted && check_end) || any(check_all): when sorted=true and v[end] is finite, falls through to the full any scan. The v[end] fast-path never fires on the happy path.

Two options:

  • Trust the contract (sorted ? check_end : any(check_all)) — O(1) when sorted, matches docstring ("can be assumed to be sorted"). Requires updating the test at test/runtests.jl:707-713 which plants NaN mid-array under sorted=true.
  • Drop the dead v[end] branch — preserves current behavior, no perf change, just clarity.
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.