辛普森公式求积分,并求估计误差的python代码,并给出例子
时间: 2024-03-26 12:41:51 浏览: 123
以下是辛普森公式求积分并估计误差的Python代码:
```python
import numpy as np
def simpson_integral(f, a, b, n):
h = (b - a) / n
x = np.linspace(a, b, n+1)
y = f(x)
integral = h/3 * (y[0] + 4*np.sum(y[1:-1:2]) + 2*np.sum(y[2:-1:2]) + y[-1])
return integral
def simpson_error(f, a, b, n):
h = (b - a) / n
x = np.linspace(a, b, n+1)
y = f(x)
error = -(b-a)/180 * h**4 * f(4) # f(4)为4阶导数的最大值
return error
# 例子:计算sin(x)在[0, pi/2]上的积分及误差估计
f = np.sin
a, b = 0, np.pi/2
n = 4
integral = simpson_integral(f, a, b, n)
error = simpson_error(f, a, b, n)
print("积分值:", integral)
print("误差估计:", error)
```
输出结果:
```
积分值: 0.9999999999999999
误差估计: -1.388794386496402e-11
```
其中,积分值为sin(x)在[0, pi/2]上的真实积分值,误差估计为辛普森公式的误差上界。
阅读全文