The Wayback Machine - https://web.archive.org/web/20240719054138/https://www.geeksforgeeks.org/monte-carlo-integration-in-python/
Open In App

Monte Carlo integration in Python

Last Updated : 10 Mar, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Monte Carlo Integration is a process of solving integrals having numerous values to integrate upon. The Monte Carlo process uses the theory of large numbers and random sampling to approximate values that are very close to the actual solution of the integral. It works on the average of a function denoted by <f(x)>.  Then we can expand <f(x)> as the summation of the values divided by the number of points in the integration and solve the Left-hand side of the equation to approximate the value of the integration at the right-hand side. The derivation is as follows.

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

Where N = no. of terms used for approximation of the values.

Now we would first compute the integral using the Monte Carlo method numerically and then finally we would visualize the result using a histogram by using the python library matplotlib.

Modules Used:

The modules that would be used are:

  • Scipy: Used to get random values between the limits of the integral. Can be installed using:
pip install scipy # for windows
or
pip3 install scipy # for linux and macos
  • Numpy: Used to form arrays and store different values. Can be installed using:
pip install numpy # for windows
or 
pip3 install numpy # for linux and macos
  • Matplotlib: Used to visualize the histogram and the result of the Monte Carlo integration.
pip install matplotlib # for windows
or 
pip3 install matplotlib # for linux and macos

Example 1:

The integral we are going to evaluate is:

Once we are done installing the modules, we can now start writing code by importing the required modules, scipy for creating random values in a range and NumPy module to create static arrays as default lists in python are relatively slow because of dynamic memory allocation. Then we defined the limits of integration which are 0 and pi (we used np.pi to get the value of pi. Then w create a static numpy array of zeros of size N using the np. zeros(N). Now we iterate over each index of array N and fill it with random values between a and b. Then we create a variable to store sum of the functions of different values of the integral variable. Now we create a function to calculate the sin of a particular value of x. Then we iterate and add up all the values returned by the function of x for different values of x to the variable integral. Then we use the formula derived above to get the results. Finally, we print the results on the final line.

Python3

# importing the modules
from scipy import random
import numpy as np
  
# limits of integration
a = 0
b = np.pi # gets the value of pi
N = 1000
  
# array of zeros of length N
ar = np.zeros(N)
  
# iterating over each Value of ar and filling 
# it with a random value between the limits a
# and b
for i in range (len(ar)):
    ar[i] = random.uniform(a,b)
  
# variable to store sum of the functions of 
# different values of x
integral = 0.0
  
# function to calculate the sin of a particular
# value of x
def f(x):
    return np.sin(x)
  
# iterates and sums up values of different functions
# of x
for i in ar:
    integral += f(i)
  
# we get the answer by the formula derived adobe
ans = (b-a)/float(N)*integral
  
# prints the solution
print ("The value calculated by monte carlo integration is {}.".format(ans))

                    

Output:

The value calculated by monte carlo integration is 2.0256756150767035.

The value obtained is very close to the actual answer of the integral which is 2.0. 

Now if we want to visualize the integration using a histogram, we can do so by using the matplotlib library. Again we import the modules, define the limits of integration and write the sin function for calculating the sin value for a particular value of x. Next, we take an array that has variables representing every beam of the histogram. Then we iterate through N values and repeat the same process of creating a zeros array, filling it with random x values, creating an integral variable adding up all the function values, and getting the answer N times, each answer representing a beam of the histogram. The code is as follows:

Python3

# importing the modules
from scipy import random
import numpy as np
import matplotlib.pyplot as plt
  
# limits of integration
a = 0
b = np.pi # gets the value of pi
N = 1000
  
# function to calculate the sin of a particular 
# value of x
def f(x):
    return np.sin(x)
  
# list to store all the values for plotting 
plt_vals = []
  
# we iterate through all the values to generate 
# multiple results and show whose intensity is 
# the most.
for i in range(N):
    
    #array of zeros of length N
    ar = np.zeros(N)
  
    # iterating over each Value of ar and filling it
    # with a random value between the limits a and b
    for i in range (len(ar)):
        ar[i] = random.uniform(a,b)
  
    # variable to store sum of the functions of different
    # values of x
    integral = 0.0
  
    # iterates and sums up values of different functions 
    # of x
    for i in ar:
        integral += f(i)
  
    # we get the answer by the formula derived adobe
    ans = (b-a)/float(N)*integral
  
    # appends the solution to a list for plotting the graph
    plt_vals.append(ans)
  
# details of the plot to be generated
# sets the title of the plot 
plt.title("Distributions of areas calculated")
  
# 3 parameters (array on which histogram needs 
plt.hist (plt_vals, bins=30, ec="black") 
  
# to be made, bins, separators colour between the
# beams)
# sets the label of the x-axis of the plot
plt.xlabel("Areas")
plt.show() # shows the plot

                    

Output:

Here as we can see, the most probable results according to this graph would be 2.023 or 2.024 which is again quite close to the actual solution of this integral that is 2.0.  

Example 2:

The integral we are going to evaluate is: 

The implementation would be the same as the previous question, only the limits of integration defined by a and b would change and also the f(x) function that returns the corresponding function value of a specific value would now return x^2 instead of sin (x). The code for this would be: 

Python3

# importing the modules
from scipy import random
import numpy as np
  
# limits of integration
a = 0
b = 1
N = 1000
  
# array of zeros of length N
ar = np.zeros(N)
  
# iterating over each Value of ar and filling
# it with a random value between the limits a 
# and b
for i in range(len(ar)):
    ar[i] = random.uniform(a, b)
  
# variable to store sum of the functions of 
# different values of x
integral = 0.0
  
# function to calculate the sin of a particular 
# value of x
def f(x):
    return x**2
  
# iterates and sums up values of different 
# functions of x
for i in ar:
    integral += f(i)
  
# we get the answer by the formula derived adobe
ans = (b-a)/float(N)*integral
  
# prints the solution
print("The value calculated by monte carlo integration is {}.".format(ans))

                    

Output:

The value calculated by monte carlo integration is 0.33024026610116575.

The value obtained is very close to the actual answer of the integral which is 0.333.

Now if we want to visualize the integration using a histogram again, we can do so by using the matplotlib library as we did for the previous expect in this case the f(x) functions return x^2 instead of sin(x), and the limits of integration change from 0 to 1.  The code is as follows:

Python3

# importing the modules
from scipy import random
import numpy as np
import matplotlib.pyplot as plt
  
# limits of integration
a = 0
b = 1
N = 1000
  
# function to calculate x^2 of a particular value 
# of x
def f(x):
    return x**2
  
# list to store all the values for plotting 
plt_vals = []
  
# we iterate through all the values to generate
# multiple results and show whose intensity is 
# the most. 
for i in range(N):
    
    # array of zeros of length N
    ar = np.zeros(N)
  
    # iterating over each Value of ar and filling
    # it with a random value between the limits a 
    # and b
    for i in range (len(ar)):
        ar[i] = random.uniform(a,b)
  
    # variable to store sum of the functions of 
    # different values of x
    integral = 0.0
  
    # iterates and sums up values of different functions
    # of x
    for i in ar:
        integral += f(i)
  
    # we get the answer by the formula derived adobe
    ans = (b-a)/float(N)*integral
  
    # appends the solution to a list for plotting the 
    # graph
    plt_vals.append(ans)
  
# details of the plot to be generated
# sets the title of the plot 
plt.title("Distributions of areas calculated")
  
# 3 parameters (array on which histogram needs 
# to be made, bins, separators colour between 
# the beams)
plt.hist (plt_vals, bins=30, ec="black")
  
# sets the label of the x-axis of the plot
plt.xlabel("Areas")
plt.show() # shows the plot

                    

Output:

Here as we can see, the most probable results according to this graph would be 0.33 which is almost equal (equal in this case, but it generally doesn’t occur) to the actual solution of this integral that is 0.333.



Previous Article
Next Article

Similar Reads

Python Program to Integrate a Chebyshev Series and Set the Integration Constant
In this article, we will discuss how to integrate a Chebyshev Series and set the integration constant To perform Chebyshev integration, NumPy provides a function called chebyshev.chebint which can be used to integrate Chebyshev series. Syntax: chebyshev.chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0) Parameters: c - Array of Chebyshev series coefficie
3 min read
Integrate a Chebyshev series and set the order of integration using NumPy in Python
In this article, we will discuss how to integrate the Chebyshev series and set the order of integration in Python and NumPy. chebyshev.chebint method Chebyshev polynomials are significant in approximation theory because the Chebyshev nodes are used as matching points for optimizing polynomial interpolation. To perform Chebyshev Integration, NumPy p
4 min read
Integrate a Hermite series and multiply the result by a scalar before the integration constant is added using NumPy in Python
In this article, we will see how to integrate a Hermite series and multiply the result by a scalar before the integration constant is added in Python. hermite.hermint method Hermite nodes are utilised as matching points for optimising polynomial interpolation, Hermite polynomials are important in approximation theory. NumPy has a function called he
2 min read
Integrate a Laguerre series and multiply the result by a scalar before the integration constant is added in Python
In this article, we will see how to integrate a Laguerre series and multiply the result by a scalar before the integration constant is added in python. laguerre.lagint method Laguerre polynomials arise in quantum theory because the Laguerre nodes are used as matching points for optimizing polynomial interpolation. To perform Hermite Integration, Nu
2 min read
Django Google Calender Integration in Python
Google Calendar is a fantastic tool for managing your schedule. It's user-friendly and helps you keep track of all your important events and appointments. You can create events, set reminders, and receive notifications so you don't miss anything. In this article, we will see how we can integrate Google Calendar with Django in Python. Google Calenda
6 min read
Swagger Integration with Python Django
Integrating Swagger with Django REST Framework can be quite useful for documenting and testing your API. One popular tool for integrating Swagger with Django REST Framework is drf-yasg (Yet Another Swagger Generator). In this article, we will see how to integrate Swagger with the Django REST framework. Swagger Integration With Python DjangoBelow is
2 min read
Integrating Python Swagger with Continuous Integration
The Continuous Integration (CI) has become a standard practice. It enables teams to build, test, and deploy code changes rapidly and reliably. The Swagger on the other hand is a powerful framework for designing, building, and documenting APIs. Integrating Swagger with the CI pipelines can streamline the API development process and ensure consistenc
4 min read
SciPy - Integration of a Differential Equation for Curve Fit
In Machine Learning, often what we do is gather data, visualize it, then fit a curve in the graph and then predict certain parameters based on the curve fit. If we have some theoretical data we can use curve fitting from the verified dataset to extract the equation and verify it. So to find the equation of a curve of any order be it linear, quadrat
2 min read
SciPy - Integration
Scipy is the scientific computing module of Python providing in-built functions on a lot of well-known Mathematical functions. The scipy.integrate sub-package provides several integration techniques including an ordinary differential equation integrator. Finding Integration using scipy.integrate Numerical Integration is the approximate computation
4 min read
Razorpay Integration in Django
Payments are an integral part of the online ecosystem, be it at e-commerce stores to process the orders or a simple donation to someone. Integrating a payment gateway into your website can be a tedious process. Let us have a look at how you can integrate Razorpay into a Django website. What are we building? We will build a basic replica of Buy Me C
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg