Skip to main content

How to perform numerical integration using SciPy.

Here's a step-by-step tutorial on how to perform numerical integration using SciPy:

Step 1: Import the necessary libraries

To get started, you need to import the necessary libraries. In this case, we'll need the scipy library for numerical integration and the numpy library for mathematical operations.

import numpy as np
from scipy import integrate

Step 2: Define the function to be integrated

Next, you need to define the function that you want to integrate. Let's say we want to integrate the function f(x) = x^2 over the interval [0, 1].

def f(x):
return x**2

Step 3: Perform the numerical integration

Now, you can perform the numerical integration using the quad function from scipy.integrate. The quad function takes the function to be integrated and the lower and upper limits of integration as arguments.

result, error = integrate.quad(f, 0, 1)

The quad function returns two values: the result of the integration and an estimate of the error. In this case, result will contain the value of the definite integral of f(x) over the interval [0, 1], and error will contain an estimate of the error in the result.

Step 4: Print the result

Lastly, you can print the result of the integration.

print("The result of the integration is:", result)
print("The estimated error is:", error)

That's it! You have successfully performed numerical integration using SciPy. The complete code is as follows:

import numpy as np
from scipy import integrate

def f(x):
return x**2

result, error = integrate.quad(f, 0, 1)

print("The result of the integration is:", result)
print("The estimated error is:", error)

You can modify the function f(x) and the limits of integration to perform different numerical integrations.