0
$\begingroup$

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))```
$\endgroup$
2
$\begingroup$

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.

For other quadrature rules, there are other error estimators derived. Like for Gauss-Legendre quadrature rules the difference between GL5 and GL4 is a good estimator (respectively, 5th and 4th degree Gauss-Legendre quadrature rules). You may need to pick up book on numerical analysis/scientific computing to learn the details. I do not know anything off the top of my head though.

| cite | improve this answer | |
$\endgroup$
  • $\begingroup$ Thanks! I'll do some research and see what I can come up with. $\endgroup$ – Kishan Bhatt May 12 at 6:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.