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

added a weighted mean #57

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
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
37 changes: 37 additions & 0 deletions src/NaNMath.jl
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,27 @@ NaNMath.mean([1., 2., NaN]) # result: 1.5
function mean(x::AbstractArray{T}) where T<:AbstractFloat
return mean_count(x)[1]
end

"""
NaNMath.mean(A, W)

##### Args:
* `A`: An array of floating point numbers
* `W`: An array of floating point weights corresponding to the values of `A`

##### Returns:
* Returns the arithmetic weighted mean of all elements in the array, ignoring NaN's.

##### Examples:
```julia
using NaNMath
NaNMath.mean([1., 2., NaN], [1., .5, 1]) # result: 1.0
```
"""
function mean(x::AbstractArray{T}, w::AbstractArray{T}) where T<:AbstractFloat
return mean_count(x, w)[1]
end


"""
Returns a tuple of the arithmetic mean of all elements in the array, ignoring NaN's,
Expand All @@ -229,6 +250,22 @@ function mean_count(x::AbstractArray{T}) where T<:AbstractFloat
return (result, count)
end

"""
Returns a tuple of the arithmetic mean of all elements in the array, ignoring NaN's,
and the sum of weights of non-NaN values and non-NaN weights in the array.
"""
function mean_count(x::AbstractArray{T}, w::AbstractArray{T}) where T<:AbstractFloat
zx, zw = zero(eltype(x)), zero(eltype(z))
sum = zx
weightsum = zw
@simd for i, j in zip(x, w)
weightsum += ifelse(isnan(i)||isnan(j), zw, j)
sum += ifelse(isnan(i)||isnan(j), z, i)
end
result = sum / count
return (result, count)
end

"""
NaNMath.var(A)

Expand Down