Average multiple evaluations of the same function

Suppose we have a function f(input) that transforms input (a long list of input arguments) into an output (a long tuple), depending on some (hidden) random values.
A very minimalist example is the randn function.

Is there an elegant way to compute the average of the output tuple over multiple evaluations?

Thanks and may you have a nice day;

It depends on the type of output, but something like:

julia> function average_over(f::Function, args...; n::Int)
           return reduce(.+, f(args...) for _ in 1:n) ./ n
       end
average_over (generic function with 1 method)

julia> foo(args...) = map(a -> a .+ randn(2), args)
foo (generic function with 1 method)

julia> average_over(foo, 1, 2; n = 10)
([0.8054566798422351, 1.1462985508680306], [2.8200773922538627, 2.0001120212986656])
1 Like

How about mean(f(input) for _ in 1:10)?

E.g. mean(randn(100) for _ in 1:10) just works. Depending on the type of the output of f this may or may not work.

Edit: mean is in Statistics.jl

3 Likes