0
0
SciPydata~5 mins

Single integral (quad) in SciPy

Choose your learning style9 modes available
Introduction

We use single integrals to find the total amount or area under a curve. It helps us understand how things add up continuously.

Calculating the total distance traveled when speed changes over time.
Finding the area under a curve in a graph, like total sales over a period.
Estimating the accumulated quantity, such as total rainfall over a day.
Computing probabilities in continuous distributions.
Determining work done when force varies along a path.
Syntax
SciPy
from scipy.integrate import quad

result, error = quad(function, lower_limit, upper_limit)

function is the function you want to integrate.

lower_limit and upper_limit define the range of integration.

Examples
Integrate x squared from 0 to 1.
SciPy
from scipy.integrate import quad

def f(x):
    return x**2

result, error = quad(f, 0, 1)
Integrate x cubed from 1 to 2 using a lambda function.
SciPy
result, error = quad(lambda x: x**3, 1, 2)
Integrate sine function from 0 to π.
SciPy
import math
result, error = quad(math.sin, 0, math.pi)
Sample Program

This program calculates the integral of e-x² from 0 to 1, which is a common function in probability and statistics.

SciPy
from scipy.integrate import quad
import math

def integrand(x):
    return math.exp(-x**2)

result, error = quad(integrand, 0, 1)
print(f"Integral result: {result}")
print(f"Estimated error: {error}")
OutputSuccess
Important Notes

The quad function returns two values: the integral result and an estimate of the error.

Always check the error to understand how accurate the result is.

You can integrate any function that takes a single variable as input.

Summary

Single integrals help find total amounts or areas under curves.

Use scipy.integrate.quad to calculate integrals easily in Python.

The function returns both the integral value and an error estimate.