Predictive Hacks

Monte Carlo Integration in Python

monte carlo integration in python

We will provide examples of how you solve integrals numerically in Python. Let’s recall from statistics that the mean value can be calculated as.

\( E(X) = \frac{1}{b-a} \int_{a}^{b}f(x)dx\)

\((b-a) E(X) = \int_{a}^{b} f(x) dx\)

\((b-a)\frac{1} {N}\sum_{i}f(x_i) \approx \int_{a}^{b}f(x)dx \)

This implies that we can find an approximation of an interval by calculating the average value times the range that we intergate.


Example of Monte Carlo Integration

Let’s say that we want to calculate the following integral where from WolframAlpha we get the solution:

\(\int_{5}^{20}\frac{x}{(x+1)^3}dx = \frac{125}{1176}\approx 0.10629\)


Solution with Python

import numpy as np
Ν = 100000000
a = 5
b = 20
x = np.random.uniform(a,b,Ν)

f_x = x/((1+x)**3)

print(np.mean(f_x)*(b-a))
0.10629043477066367

Not bad! The Month Carlo Integration returned a very good approximation!

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

connect with sql
R

How to Connect R with SQL

Need to Connect R with SQL It is common for Data Analysts/Scientists to connect R with SQL. For that reason,

[the_ad_group id="232"]
[the_ad id="2133"]