Skip to content

computing the weighted mean along dimension dims. #180

@FerreolS

Description

@FerreolS

I would like to compute weighted mean along a given dimension as it is possible with mean.
The following function implements this feature

function weightedmean_dims(iterable; dims::Union{Colon,Int}=:)
           v = [el.val for el in iterable]
           w = [inv(el.err)^2 for el in iterable]
           invsumw = inv.(sum(w; dims=dims))
           return measurement.(sum(v .* w; dims=dims) .* invsumw, sqrt.(invsumw))
 end

However it is a bit less efficient:

julia> N  = 1_000_000;

julia> m = measurement.(randn(N,5), rand(N,5));

julia> @btime weightedmean(m)
  29.861 ms (8 allocations: 76.30 MiB)
-0.139496023 ± 3.0e-8

julia> @btime weightedmean_dims(m)
  37.372 ms (11 allocations: 114.45 MiB)
-0.139496023 ± 3.0e-8

julia> @btime weightedmean_dims(m; dims=1)
  36.914 ms (22 allocations: 114.45 MiB)
1×5 Matrix{Measurement{Float64}}:
 -0.0789744±3.4e-8  -0.466307±7.2e-8  -0.0655678±5.7e-7  0.720289±3.3e-7  0.0534679±2.9e-7

Any suggestion to improve the performance? before I do a PR (if requested)

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