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;
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?


2 Answers 2


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)

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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.