Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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
up vote 10 down vote accepted

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)
share|improve this answer

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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