【发布时间】:2021-04-23 09:38:36
【问题描述】:
我正在键入代码以通过梯形方法和辛普森规则以及给定输入“n”的情况下这些值的绝对差来生成积分值。如果 i 在 (1, 19) 范围内,则“n”输入本身就是 n = 2 ** i 的函数。
我的代码输出的表格如下
n Trapezoidal Simpson Absolute Difference
------ ------------- --------- ---------------------
2 -0.929894 -0.68338 0.246515
4 -0.687139 -0.606221 0.0809183
8 -0.614581 -0.590396 0.024186
16 -0.594187 -0.587389 0.00679814
32 -0.588796 -0.587 0.00179688
64 -0.587422 -0.586964 0.000458234
128 -0.587076 -0.586961 0.000115222
256 -0.58699 -0.586961 2.88492e-05
512 -0.586968 -0.586961 7.21507e-06
1024 -0.586962 -0.586961 1.80394e-06
2048 -0.586961 -0.586961 4.50996e-07
4096 -0.586961 -0.586961 1.1275e-07
8192 -0.586961 -0.586961 2.81874e-08
16384 -0.586961 -0.586961 7.04687e-09
32768 -0.586961 -0.586961 1.7617e-09
65536 -0.586961 -0.586961 4.40314e-10
131072 -0.586961 -0.586961 1.10276e-10
262144 -0.586961 -0.586961 2.76881e-11
524288 -0.586961 -0.586961 7.86082e-12
但是,我希望表中的值全部四舍五入为 7 个十进制值,并且不使用 e/E 进行格式化,以便我的表如下所示:
n Trapezoidal Simpson Absolute Difference
------------------------------------------------------------------------
2 -0.9298943 -0.6833796 0.2465147
4 -0.6871394 -0.6062211 0.0809183
8 -0.6145815 -0.5903955 0.0241860
16 -0.5941871 -0.5873889 0.0067981
32 -0.5887964 -0.5869996 0.0017969
64 -0.5874217 -0.5869635 0.0004582
128 -0.5870761 -0.5869609 0.0001152
256 -0.5869895 -0.5869607 0.0000288
512 -0.5869679 -0.5869607 0.0000072
1024 -0.5869625 -0.5869607 0.0000018
2048 -0.5869611 -0.5869607 0.0000005
4096 -0.5869608 -0.5869607 0.0000001
8192 -0.5869607 -0.5869607 0.0000000
16384 -0.5869607 -0.5869607 0.0000000
32768 -0.5869607 -0.5869607 0.0000000
65536 -0.5869607 -0.5869607 0.0000000
131072 -0.5869607 -0.5869607 0.0000000
262144 -0.5869607 -0.5869607 0.0000000
524288 -0.5869607 -0.5869607 0.0000000
下面是我用来获取表格的代码
from numpy import arange
import numpy as np
from numpy import subtract
from tabulate import tabulate
from math import cos, sin
def trapezoidal(f, n, a, b):
h = (b-a)/ n
x = a + arange(n + 1) * h
integral_approx = 0.5 * h * (f(x[0]) + f(x[n]))
for i in arange(1, n):
integral_approx = integral_approx + h * f(x[i])
return integral_approx
def simpson(f, n, a, b):
if n % 2 is not 0:
return None
h = (b - a)/n
first = f(a)
last = f(b)
x = a
summ = 0
for i in range(n - 1):
x += h
value = f(x)
if i % 2 == 0:
summ += 4 * value
else:
summ += 2 * value
integral_approx = (h/3) * (first + summ + last)
return integral_approx
a = 0.1
b = pi/2
f = lambda x: (cos(x)*np.log(sin(x)))/((sin(x)**2) + 1)
d = []
for i in range(1, 20):
n = 2**i
absdiff = abs(subtract(trapezoidal(f, n, a, b), simpson(f, n, a, b)))
d.append([n, trapezoidal(f, n, a, b), simpson(f, n, a, b), absdiff])
print(tabulate(d, headers = ["n", "Trapezoidal", "Simpson", "Absolute Difference"]))
由于我格式化函数的方式,我不确定是否存在差异。如果可以的话,请帮忙。
【问题讨论】: