Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solve the overflow in mean() on integers by promoting accumulator #25

Merged
merged 19 commits into from
Apr 14, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/Statistics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,12 @@ function _mean(f, A::AbstractArray, dims=:)
n = mapreduce(i -> size(A, i), *, unique(dims); init=1)
end
x1 = f(first(A)) / 1
return sum(x -> _mean_promote(x1, f(x)), A, dims=dims) / n
result = sum(x -> _mean_promote(x1, f(x)), A, dims=dims)
if dims === (:)
result /= n
else
result ./= n
end
kagalenko-m-b marked this conversation as resolved.
Show resolved Hide resolved
end
kagalenko-m-b marked this conversation as resolved.
Show resolved Hide resolved

function mean(r::AbstractRange{<:Real})
Expand Down
10 changes: 7 additions & 3 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,13 @@ end
@test mean(x) == sum(x) / length(x)
end
@test mean(Number[1, 1.5, 2+3im]) === 1.5+1im # mixed-type array
kagalenko-m-b marked this conversation as resolved.
Show resolved Hide resolved
@test (@inferred mean(Int[])) === 0.0/0
@test (@inferred mean(Float64[])) === 0.0/0
@test (@inferred mean(Float32[])) === 0.0f0/0
@test mean(v for v in Number[1, 1.5, 2+3im]) === 1.5+1im
@test (@inferred mean(Int[])) === 0/0
@test (@inferred mean(Float32[])) === 0.f0/0
@test (@inferred mean(Float64[])) === 0/0
@test (@inferred mean(filter(x -> true, Int[]))) === 0/0
@test (@inferred mean(filter(x -> true, Float32[]))) === 0.f0/0
@test (@inferred mean(filter(x -> true, Float64[]))) === 0/0
kagalenko-m-b marked this conversation as resolved.
Show resolved Hide resolved
end

@testset "mean/median for ranges" begin
Expand Down