Skip to content

Commit

Permalink
Prevent overflow in mean(::AbstractRange) and relax type constraint. (
Browse files Browse the repository at this point in the history
#150)

Co-authored-by: Chunji Wang <chunji.wang@samsung.com>
Co-authored-by: Vincent Yu <v@v-yu.com>
  • Loading branch information
3 people committed Sep 14, 2023
1 parent a88ae4f commit b8ea3d2
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 @@ -196,9 +196,9 @@ function _mean(f, A::AbstractArray, dims::Dims=:) where Dims
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

##### variances #####
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 b8ea3d2

Please sign in to comment.