# Average multiple evaluations of the same function

**URL:** <https://discourse.julialang.org/t/average-multiple-evaluations-of-the-same-function/126009>\
**Category:** General Usage\
**Tags:** metaprogramming\
**Created:** [February 17, 2025, 9:00pm UTC](https://discourse.julialang.org/t/average-multiple-evaluations-of-the-same-function/126009 "2025-02-17T21:00:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ignace](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ignace/32/24275_2.png) [@ignace](https://discourse.julialang.org/u/ignace)\
**Post date:** [February 17, 2025, 9:00pm UTC](https://discourse.julialang.org/t/average-multiple-evaluations-of-the-same-function/126009/1 "2025-02-17T21:00:16Z")

</div>

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](https://docs.julialang.org/en/v1/stdlib/Random/#Base.randn).

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

Thanks and may you have a nice day;

---

<div class="post-metadata">

**Author:** ![odow](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/odow/32/28685_2.png) [@odow](https://discourse.julialang.org/u/odow)\
**Post date:** [February 17, 2025, 9:09pm UTC](https://discourse.julialang.org/t/average-multiple-evaluations-of-the-same-function/126009/2 "2025-02-17T21:09:38Z")

</div>

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

```Julia
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])

```

---

<div class="post-metadata">

**Author:** ![abraemer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/abraemer/32/51403_2.png) [@abraemer](https://discourse.julialang.org/u/abraemer)\
**Post date:** [February 17, 2025, 9:09pm UTC](https://discourse.julialang.org/t/average-multiple-evaluations-of-the-same-function/126009/3 "2025-02-17T21:09:41Z")

</div>

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
