Skip to content

Commit

Permalink
Merge pull request #164 from aplavin/patch-1
Browse files Browse the repository at this point in the history
propagate NaN value in median
  • Loading branch information
andreasnoack committed May 26, 2024
2 parents 71ebe28 + 517afa6 commit 6e3d223
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Statistics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -835,7 +835,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

0 comments on commit 6e3d223

Please sign in to comment.