Integration in Python
quad for a definite integral, solve_ivp for a differential equation.
import numpy as np
from scipy import integrate
value, error = integrate.quad(lambda x: np.exp(-x ** 2), 0, np.inf)
print(round(value, 8), f"{error:.1e}", round(np.sqrt(np.pi) / 2, 8))
x = np.linspace(0, np.pi, 101)
print(round(integrate.trapezoid(np.sin(x), x), 6))
print(round(integrate.simpson(np.sin(x), x=x), 6))
solution = integrate.solve_ivp(lambda t, y: -0.5 * y, t_span=(0, 10),
y0=[100.0], t_eval=[0, 5, 10])
print(solution.y[0].round(3), solution.success)
How it works
quadreturns the value and an error estimate.trapezoidandsimpsonintegrate samples, not functions.solve_ivpwalks an ODE forward from initial conditions.
Keywords and builtins used here
aslambdaprintround
The run, in numbers
- Lines
- 13
- Characters to type
- 468
- Tokens
- 186
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 101 seconds.
Step 1 of 2 in Calculus & interpolation, step 14 of 23 in Scientific computing with SciPy.