typestar

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

  1. quad returns the value and an error estimate.
  2. trapezoid and simpson integrate samples, not functions.
  3. solve_ivp walks an ODE forward from initial conditions.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 2 in Calculus & interpolation, step 14 of 23 in Scientific computing with SciPy.

← Previous Next →