JuliaMath / NaNMath.jl

Julia math built-ins which return NaN and accumulator functions which ignore NaN
Other
52 stars 26 forks source link

Faster `mean` #42

Closed Moelf closed 3 years ago

Moelf commented 3 years ago
julia> function my_mean_count(x::AbstractArray{T}) where T<:AbstractFloat
           z = zero(eltype(x))
           sum = z
           count = 0
           @simd for i in x
               count += ifelse(isnan(i), 0, 1)
               sum += ifelse(isnan(i), z, i)
           end
           result = sum / count
           return (result, count)
       end

this runs 2x faster (on an AMD cpu, so this is expected). Is this a reasonable update(?) to what we already have?

mlubin commented 3 years ago

Seems safe enough. Be careful about division by zero when count = 0.

Moelf commented 3 years ago

that's how we recover the NaN if all elements are NaN actually.

mlubin commented 3 years ago

Is it guaranteed that any AbstractFloat defines 0.0/0 = NaN?

Moelf commented 3 years ago
julia> for T in subtypes(AbstractFloat)
           @assert isnan(zero(T)/0)
       end

I think so. Because it first promote 0 to the float 0.0 of type T