# How to implement tolerance checking within a for loop whilst performing a numerical integration using a trapezoidal function?

Currently, I have this working code where I have been able to successfully calculate the integration for standard results. But in terms of precision, how could I achieve a good tolerance?

import numpy as np
import matplotlib.pyplot as plt

def A0(a, b, fa, fb):
h0 = b - a
A0 = 0.5 * h0 * (fa + fb)
return A0

def An(f,a,b,n):

#Make step size h
h = (b-a)/n

#Apply formula
sum = 0.5 * (f(a) + f(b))

for i in range(1,n, 2):
sum += 4 * f( a + i * h)
print (sum * (h /3))
for i in range (2, n-1, 2):
sum += 2 * f(a + i * h)
print (sum * (h /3))

An = sum * (h /3)

return (An)

def x_sq(x):
return np.power(x,2)

def sin_x(x):
return np.sin(x)

def exp_minus_xsq(x):
return (np.exp(np.power(-x,2)))

# User input for the limits they want to calculate integral from and to
a = (float(input("What value do you choose for a?")))
b = (float(input("What value do you choose for b?")))
n = int(input("How many divisions, n, would you like to apply to the routine?"))

# Calculate the required step size for the use in the rule
h = b - a / n
i = 0

print("integrating x^2 from ", a, " to ", b, " = ",A0(a, b, x_sq(a), x_sq(b)))
print("integrating sin x from ", a, " to ", b, " = ",A0(a, b, sin_x(a), sin_x(b)))
print("integrating e^-(x^2) from ", a, " to ", b, " = ",A0(a, b, exp_minus_xsq(a), exp_minus_xsq(b)))

print ("Using",  n,  "number of Trapezoids, Integrating from ", a, "to", b, "A = ", An(x_sq, a, b, n))$$$$


You are looking for adaptive quadrature techniques. Wikipedia article is decent at explaining that; https://en.wikipedia.org/wiki/Adaptive_quadrature . Basically, you need an error estimator to decide whether to subdivide or not. For the trapezoidal rule, fortunately, abs(An(f,a,b,2)-An(f,a,b,1))` is a good error estimator for $$|I_1-I|$$, assuming your function is sufficiently smooth and well-behaving (no sharp derivatives, no strong oscillations and robust to floating point errors). If I remember correctly this can be proven through Taylor's series expansions but I might be wrong.