How to Compute the mean of a distribution using Python and Numpy?


In the last post, we have defined a function to compute the numerical integration in Python and Numpy. This tutorial will guide you how to compute the mean of the distribution using this function.

Remember, if x is a random variable with distribution p(x) then its mean value, E(x) is given by integrating x.p(x) between plus and minus infinity.

We now make a new function called compute_mean that takes the distribution as an input function. The compute_mean will also take the upper and lower bounds and N slices parameters that will be passed on to the integrate function. So define a new function with the following signature,

function m = compute_mean(f, a, b, N)

Inside the body of this function we will use our function integrate to evaluate the integral of x.f(x).

But how can we pass x.f(x) to integrate? integrate() takes the function that we want to integrate as input, but the problem is that we haven’t written a function that directly evaluates x.f(x).

One solution is to use a Python inner function to define a new function inside the compute_mean function body.

compute_mean has been passed a function called f and we want to write a new function that evaluates x.f(x). Elementwise multiplication of two vectors can be done using numpy’s multiply() function. So our inner-function will look like

def xfx(x):
    return np.multiply(f(x), x)

Note that f2() did not need to be passed the function f() as it inherited from the scope of the containing function compute_mean()
Once this function has been defined we can now integrate it using our integrate function and so compute the mean, i.e.

def integrate(f, a, b, N):
    x = np.linspace(a, b, N)
    fx = f(x)
    area = np.sum(fx)*(b-a)/N
    return area

def compute_mean(f, a, b, N):
    def xfx(x):
        return np.multiply(x, f(x))
    mean = integrate(xfx, a, b, N)
    return mean

compute_mean(np.sin, 0, np.pi/2, 50)

This gives:

0.99995887309680154

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
470 words
Last Post: How to Compute Numerical integration in Numpy (Python)?
Next Post: C++ Function to Compute Numerical Integral Using Function Pointers

The Permanent URL is: How to Compute the mean of a distribution using Python and Numpy?

Leave a Reply