The Average Wait

IntegralsMedium+20 XP+20

The Average Wait

A delivery app tracks how long a courier takes to reach a restaurant: a continuous time XXX, in minutes, that always lands somewhere between aaa and bbb. The data team has worked out the shape of its density curve, a function shape(x) that is never negative, but they never scaled it. The area under it is generally not 1.

The average of a continuous quantity is an integral: every possible value, weighted by its density, added up.

average of X=∫abx f(x) dx\text{average of } X = \int_a^b x \, f(x)\, dxaverage of X=∫ab​xf(x)dx

Here fff has to be a genuine density curve: never negative, and enclosing a total area of exactly 1.

Task: write density_mean(shape, a, b, n) that estimates the average of XXX with rectangles and returns it rounded to 4 decimal places.

  • shape is a Python function that takes one number and returns one number: shape(2.5) is the height of the curve at x=2.5x = 2.5x=2.5.
  • Split [a,b][a, b][a,b] into n rectangles of equal width.
  • Take each rectangle's height at the middle of its strip, not at either edge.
  • Use these same n slices for every area you estimate.

For example, for the shape x(4−x)2x(4 - x)^2x(4−x)2 on [0,4][0, 4][0,4] with 4 rectangles, the answer is 1.5568.

Examples

shape = lambda x: x * (4 - x) ** 2
a = 0
b = 4
n = 4
returns 1.5568
shape = lambda x: 3.0
a = 2
b = 8
n = 6
returns 5.0

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run