Skip to content

Commit b8ea3d2

Browse files
chunjiwChunji Wangvyu
authored
Prevent overflow in mean(::AbstractRange) and relax type constraint. (#150)
Co-authored-by: Chunji Wang <[email protected]> Co-authored-by: Vincent Yu <[email protected]>
1 parent a88ae4f commit b8ea3d2

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

src/Statistics.jl

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -196,9 +196,9 @@ function _mean(f, A::AbstractArray, dims::Dims=:) where Dims
196196
end
197197
end
198198

199-
function mean(r::AbstractRange{<:Real})
200-
isempty(r) && return oftype((first(r) + last(r)) / 2, NaN)
201-
(first(r) + last(r)) / 2
199+
function mean(r::AbstractRange{T}) where T
200+
isempty(r) && return zero(T)/0
201+
return first(r)/2 + last(r)/2
202202
end
203203

204204
##### variances #####

test/runtests.jl

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,8 +194,16 @@ end
194194
@test f(2:0.1:n) f([2:0.1:n;])
195195
end
196196
end
197-
@test mean(2:1) === NaN
198-
@test mean(big(2):1) isa BigFloat
197+
@test mean(2:0.1:4) === 3.0 # N.B. mean([2:0.1:4;]) != 3
198+
@test mean(LinRange(2im, 4im, 21)) === 3.0im
199+
@test mean(2:1//10:4) === 3//1
200+
@test isnan(@inferred(mean(2:1))::Float64)
201+
@test isnan(@inferred(mean(big(2):1))::BigFloat)
202+
z = @inferred(mean(LinRange(2im, 1im, 0)))::ComplexF64
203+
@test isnan(real(z)) & isnan(imag(z))
204+
@test_throws DivideError mean(2//1:1)
205+
@test mean(typemax(Int):typemax(Int)) === float(typemax(Int))
206+
@test mean(prevfloat(Inf):prevfloat(Inf)) === prevfloat(Inf)
199207
end
200208

201209
@testset "var & std" begin

0 commit comments

Comments
 (0)