Skip to content

Commit

Permalink
Prevent overflow in mean(::AbstractRange)
Browse files Browse the repository at this point in the history
and relax type constraint
  • Loading branch information
Chunji Wang committed Sep 1, 2023
1 parent 04e5d89 commit b9f3237
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
6 changes: 3 additions & 3 deletions src/Statistics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -197,9 +197,9 @@ if !isdefined(Base, :mean)
end
end

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

Expand Down
12 changes: 10 additions & 2 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,16 @@ end
@test f(2:0.1:n) f([2:0.1:n;])
end
end
@test mean(2:1) === NaN
@test mean(big(2):1) isa BigFloat
@test mean(2:0.1:4) === 3.0 # N.B. mean([2:0.1:4;]) != 3
@test mean(LinRange(2im, 4im, 21)) === 3.0im
@test mean(2:1//10:4) === 3//1
@test isnan(@inferred(mean(2:1))::Float64)
@test isnan(@inferred(mean(big(2):1))::BigFloat)
z = @inferred(mean(LinRange(2im, 1im, 0)))::ComplexF64
@test isnan(real(z)) & isnan(imag(z))
@test_throws DivideError mean(2//1:1)
@test mean(typemax(Int):typemax(Int)) === float(typemax(Int))
@test mean(prevfloat(Inf):prevfloat(Inf)) === prevfloat(Inf)
end

@testset "var & std" begin
Expand Down

0 comments on commit b9f3237

Please sign in to comment.