From 9eb9a8e046294ce1a64f40dce2ba8b75dae284ac Mon Sep 17 00:00:00 2001 From: Jishnu Bhattacharya Date: Thu, 30 Jun 2022 10:05:50 +0530 Subject: [PATCH] avoid overflow in mean --- .gitignore | 1 + src/Statistics.jl | 5 +++-- test/runtests.jl | 9 +++++++++ 3 files changed, 13 insertions(+), 2 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..ba39cc53 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +Manifest.toml diff --git a/src/Statistics.jl b/src/Statistics.jl index 040ac972..989589c5 100644 --- a/src/Statistics.jl +++ b/src/Statistics.jl @@ -183,8 +183,9 @@ function _mean(f, A::AbstractArray, dims::Dims=:) where Dims end function mean(r::AbstractRange{<:Real}) - isempty(r) && return oftype((first(r) + last(r)) / 2, NaN) - (first(r) + last(r)) / 2 + centralval = first(r) + (last(r) - first(r)) / 2 + isempty(r) && return oftype(centralval, NaN) + centralval end median(r::AbstractRange{<:Real}) = mean(r) diff --git a/test/runtests.jl b/test/runtests.jl index 35242c27..32a39dd7 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -182,6 +182,15 @@ end end @test mean(2:1) === NaN @test mean(big(2):1) isa BigFloat + + @testset "issue #120" begin + @test mean(Int8(123):Int8(123)) == 123 + @test median(Int8(123):Int8(123)) == 123 + @test mean(Int8(126):Int8(127)) == 126.5 + @test mean(typemax(Int):typemax(Int)) == float(typemax(Int)) + @test mean(UInt8(255):UInt8(255)) == 255 + @test mean(Float16(12345):Float16(54321)) ≈ Float16(mean(Float32(12345):Float32(54321))) + end end @testset "var & std" begin