Skip to content

Allow to specify the result type of a sum #5311

Closed
@lindahua

Description

@lindahua

Currently, the sum function use the element type (except for the boolean case) of the input array as result type. This is sometimes not a desirable choice:

function mysum(R, x)
    s = zero(R)
    for v in x; s += v; end
    return s
end

julia> x = uint8(rand(1:10, 50));

julia> sum(x)
0x0000000000000122

# to prevent overflow
julia> mysum(Int, x)
290

julia> a = rand(Float32, 10^6);

julia> sum(float64(a)) - sum(a)
-0.018809685949236155

# to get higher accuracy
julia> sum(float64(a)) - mysum(0.0, a)
1.1641532182693481e-10

My proposal is to add a method like sum(R, x) where R is the user-specifed type. This won't break any existing codes, but provide the user additional choices.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions