how to numerically integrate a function in python

To numerically integrate a function in Python, you can use the quad function from the scipy.integrate module. Here is an example:

main.py
from scipy import integrate

# Define the function to be integrated
def function(x):
    return x**2

# Integrate the function
result, error = integrate.quad(function, 0, 1)

# Print the result
print("The numerical integral is", result)
237 chars
12 lines

In this example, we define a function function(x) as the function to be integrated. We then use the quad function to integrate this function. The quad function takes the function to be integrated, the lower limit of integration, and the upper limit of integration as arguments. It returns the numerical integral and an estimate of the error.

In the above code, we integrate the function x^2 from 0 to 1 and print the result. You can modify the function and the integration limits as per your requirements.

related categories

gistlibby LogSnag