Skip to content

mean() can easily overflow for general iterables #25739

Closed
@nalimilan

Description

@nalimilan

Contrary to the mean(::AbstractArray) method, the mean fallback for general iterables computes the sum without promoting the element type, meaning that overflow can easily happen:

julia> mean([typemax(Int8), typemax(Int8)])
127.0

julia> mean(x for x in [typemax(Int8), typemax(Int8)])
-1.0

Apart from being inconvenient/risky, it's inconsistent with sum:

julia> sum([typemax(Int8), typemax(Int8)])
254

julia> sum(x for x in [typemax(Int8), typemax(Int8)])
254

I think we should use promote_sys_size_add added by #22825 to choose the accumulation type, just like sum.

Metadata

Metadata

Assignees

No one assigned

    Labels

    mathsMathematical functions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions