如何在 for 循环中实现公差检查,同时使用梯形函数执行数值积分?

计算科学 Python
2021-11-29 10:37:07

目前,我有这个工作代码,我已经能够成功地计算标准结果的积分。但就精度而言,我怎样才能达到良好的公差呢?

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))```
1个回答

您正在寻找自适应正交技术。维基百科的文章很好地解释了这一点;https://en.wikipedia.org/wiki/Adaptive_quadrature基本上,您需要一个误差估计器来决定是否细分。幸运的是,梯形规则abs(An(f,a,b,2)-An(f,a,b,1))是一个很好的误差估计器|I1I|,假设您的函数足够平滑且表现良好(没有尖锐的导数,没有强烈的振荡并且对浮点错误具有鲁棒性)。如果我没记错的话,这可以通过泰勒级数展开来证明,但我可能错了。

对于其他正交规则,还有其他误差估计器派生。就像 Gauss-Legendre 正交规则一样,GL5 和 GL4 之间的差异是一个很好的估计量(分别是 5 度和 4 度 Gauss-Legendre 正交规则)。您可能需要拿起有关数值分析/科学计算的书来了解详细信息。不过,我什么都不知道。