Predictive Hacks

# 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!

### Get updates and learn from the best

R

#### The fastest way to Read and Writes file in R

Compare Read and Write files time When we are dealing with large datasets, and we need to write many csv

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,