1. 实验结果
(1)计算如下积分的近似值及误差:
(真实值约0.693147118)
(2)分别使用梯形公式、Simpson 公式、Cotes 公式以及 Romber 公式计算积分的近似值,并估计误差,结果如下:
由结果可以发现,梯形公式、Simpson 公式以及 Cotes 公式计算结果的误差越来越小。 因为定义的 Romberg 公式的输入参数包括精度要求,本次运行设置精度要求为 0.001,由结 果可见求得的值满足误差要求。
改变输入的参数,设置 Romberg 求积法的精度要求为 0.000001 后,输出表格里的计算 值相应增加,由结果可见求得的值满足精度要求。
2. 代码
test.py
from class5 import integration
new = integration()
print('梯形公式:Newton_Cotes(n=1):')
new.newton_cotes(0, 1, 'trapezoid')
print('\nSimpson公式:Newton_Cotes(n=2):')
new.newton_cotes(0, 1, 'simpson')
print('\nCotes公式:Newton_Cotes(n=4):')
new.newton_cotes(0, 1, 'cotes')
print('\nRomberg公式:')
new.Romberg(0, 1, 0.001)
class5.py
import numpy as np
import sympy
class integration(object):
"""包括: 1. Newton_Cotes(n=1,2,4); 2. Romberge求积法"""
# 被积函数
def f(self, x):
y = 1 / (1 + x)
return y
# 对函数求n阶导,用于计算误差
def dc_f(self, x_, n):
x = sympy.Symbol('x')
f = 1 / (1 + x)
return sympy.diff(f, x, n).evalf(subs={
x: x_})
# 1. Newton_Cotes(n=1,2,4)
def newton_cotes(self, a, b, mode):
if mode == 'trapezoid': # 梯形求积公式
I = (b - a) * (self.f(b