# Quickly calculating the mean / median of a function over an interval

I'd like to calculate the Mean or Median value of a function over some interval $[a,b]$. However, I can't seem to find how to do this in help. Specifically I'd like to have something that works like the following:

f = x;
funcMean[f,{x,0,1}];
out :> 0.5;


The way to actually do this is to compute the integral:

1/(b - a) * NIntegrate[f, {x, a, b}, WorkingPrecision -> 20]


But I suspect there's a built-in function to do that same? What about for calculating the Median over the same interval?

-
Sometimes you might need an option in NIntegrate which helps computing quickly approximate value, like e.g. Method -> "AdaptiveMonteCarlo", see Is it possible to calculate a Lebesgue integral in Mathematica?. – Artes Feb 17 '14 at 12:18

When there is no built-in function, it is often straightforward to build one. Here's a way to calculate the median value of an integrable function:

f[x_] := x^2; a = 1; c = 3;
FindInstance[Integrate[f[x], {x, a, b}] == Integrate[f[x], {x, b, c}], b] // N
{{b -> 2.41014}}


You already have a formula for the mean:

Integrate[f[x], {x, a, c}]/(c - a)
13/3

-

Given that the word "quickly" is in your title and that you use NIntegrate in your example, you might try the following, purely numerical approach to your problem.

findMedian[f_, {x_, a_, b_}] := Module[
{y, interpolatingFunction},
interpolatingFunction = y /. First[
NDSolve[{y'[x] == f, y[a] == 0}, y, {x, a, b}
]];
FindRoot[interpolatingFunction[x] == interpolatingFunction[b]/2,
{x, (a + b)/2, a, b}]];

findMedian[Exp[x^3], {x, 1, 3}] // Timing

(* Out: {0.002237, {x -> 2.97341}} *)


Bill's FindInstance based technique is certainly preferable, if you need an exact solution, but runs unacceptably slowly in examples where the integrand yields certain special functions or cannot be evaluated at all. Perhaps, the algebraic approach can be improved, I'm not sure.

-