From cc11ea99c3308a479eb2670733a12bfb1f408c09 Mon Sep 17 00:00:00 2001 From: Alexander Plavin Date: Tue, 12 Mar 2024 23:10:39 -0400 Subject: [PATCH 1/2] propagate NaN value in median --- src/Statistics.jl | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Statistics.jl b/src/Statistics.jl index 376fb94d..17f26c0b 100644 --- a/src/Statistics.jl +++ b/src/Statistics.jl @@ -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) From 517afa69a91441bd2b9de4f535ee672f9b7c9200 Mon Sep 17 00:00:00 2001 From: Alexander Plavin Date: Sat, 20 Apr 2024 07:49:18 -0400 Subject: [PATCH 2/2] add tests --- test/runtests.jl | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/test/runtests.jl b/test/runtests.jl index df7a15e4..e0ebc32e 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -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])) @@ -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]))