Calculating Integrals in Python

To calculate integrals of a function in Python, you can use either the "scipy" or "sympy" library. Both modules offer various tools for numerical computations, including integration.

Definite Integral

To compute a definite integral \(\int_a^b f(x) \, dx\), you can use the quad() function from scipy.integrate.

from scipy.integrate import quad

For example, let's define the function to be integrated:

def integrand(x):
    return 2*x

Set the integration limits from 0 to 1.

a = 0
b = 1

Now, compute the definite integral using the quad() function.

result, error = quad(integrand, a, b)

This function returns two values: the result of the definite integral and the associated error.

print(f"Definite integral: {result}")

Definite integral: 1.0

The estimated error is:

print(f"Estimated error: {error}")

Estimated error: 1.1102230246251565e-14

The integral of \(f(x)=2x\) over the interval (0,1) is indeed 1.0 because the antiderivative of \(f(x)=2x\) is \(F(x)=x^2\).

$$ \int_0^1 2x \, dx = [ x^2 ]_0^1 = (1)^2 - (0)^2 = 1.0 $$

Alternative Method

Another way to calculate a definite integral is by using the integrate() function from the sympy library.

from sympy import symbols, integrate

First, define the symbol "x" as the independent variable:

x = symbols('x')

Next, define the function $ f(x)=2x $ that you want to integrate:

f = 2*x

Finally, compute the integral of the function f(x) using the integrate() function:

integral = integrate(f, (x,0,1))

The first argument is the integrand function f, and the second argument is a tuple (x,0,1), which specifies the variable of integration 'x' and the integration interval (0,1).

print(integral)

1

The result is always the same: the integral of f(x)=2x over the interval (0,1) is 1.

Indefinite Integral (antiderivative)

To compute an indefinite integral, you can use sympy, a library for symbolic computation.

from sympy import symbols, integrate

First, define the symbol for the independent variable:

x = symbols('x')

Then define the function to be integrated, which in this case is \( f(x)=2x \).

f = 2*x

Now, compute the indefinite integral of the function using the integrate(f,x) function.

integral = integrate(f, x)

The first parameter is the integrand \(f=2x\), and the second parameter \(x\) is the variable of integration.

print(f"Indefinite integral: {integral}")

Indefinite integral: x**2

The indefinite integral of \(f(x)=2x\) is the antiderivative \(F(x)=x^2+c\).

$$ \int 2x \, dx = x^2 + c $$

Where 'c' is an arbitrary constant.

These are the basic methods for calculating integrals in Python using `scipy` for definite integrals and `sympy` for indefinite integrals.

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Sympy