Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

propagate NaN value in median #164

Merged
merged 2 commits into from
May 26, 2024
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 src/Statistics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -814,7 +814,8 @@ Like [`median`](@ref), but may overwrite the input vector.
function median!(v::AbstractVector)
isempty(v) && throw(ArgumentError("median of an empty array is undefined, $(repr(v))"))
eltype(v)>:Missing && any(ismissing, v) && return missing
any(x -> x isa Number && isnan(x), v) && return convert(eltype(v), NaN)
nanix = findfirst(x -> x isa Number && isnan(x), v)
isnothing(nanix) || return v[nanix]
inds = axes(v, 1)
n = length(inds)
mid = div(first(inds)+last(inds),2)
Expand Down
16 changes: 16 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,14 @@ end
@test isnan(median(Any[NaN,0.0,1.0]))
@test isequal(median([NaN 0.0; 1.2 4.5], dims=2), reshape([NaN; 2.85], 2, 1))

# the specific NaN value is propagated from the input
@test median([NaN]) === NaN
@test median([0.0,NaN]) === NaN
@test median([0.0,NaN,NaN]) === NaN
@test median([-NaN]) === -NaN
@test median([0.0,-NaN]) === -NaN
@test median([0.0,-NaN,-NaN]) === -NaN

@test ismissing(median([1, missing]))
@test ismissing(median([1, 2, missing]))
@test ismissing(median([NaN, 2.0, missing]))
Expand Down Expand Up @@ -112,6 +120,14 @@ end
@test isnan(mean([0.0,NaN]))
@test isnan(mean([NaN,0.0]))

# the specific NaN value is propagated from the input
@test mean([NaN]) === NaN
@test mean([0.0,NaN]) === NaN
@test mean([0.0,NaN,NaN]) === NaN
@test mean([-NaN]) === -NaN
@test mean([0.0,-NaN]) === -NaN
@test mean([0.0,-NaN,-NaN]) === -NaN

@test isnan(mean([0.,Inf,-Inf]))
@test isnan(mean([1.,-1.,Inf,-Inf]))
@test isnan(mean([-Inf,Inf]))
Expand Down
Loading