import pandas as pd
import numpy as np
import math
x1, k1 = np.array([[0], [2]])
x2, k2 = np.array([[0.5773502692], [1]])
x3, k3 = np.array([[0.7745966692, 0],
[0.5555555556, 0.8888888889]])
x4, k4 = np.array([[0.8611363116, 0.3399810436],
[0.3478548451, 0.6521451549]])
x5, k5 = np.array([[0.9061798459, 0.5384693101, 0],
[0.2369268851, 0.4786286705, 0.5688888889]])
x6, k6 = np.array([[0.9324695142, 0.6612093865, 0.2386191861],
[0.1713244924, 0.3607615730, 0.4679139346]])
x7, k7 = np.array([[0.9491079123, 0.7415311856, 0.4058451514, 0],
[0.1294849662, 0.2797053915, 0.3818300505, 0.4179591837]])
x8, k8 = np.array([[0.9602898565, 0.7966664774, 0.5255324099, 0.1834346425],
[0.1012285363, 0.2223810345, 0.3137066459, 0.3626837834]])
table = pd.DataFrame([[x1, k1], [x2, k2], [x3, k3], [x4, k4], [x5, k5],
[x6, k6], [x7, k7], [x8, k8]],
columns=['Xk', 'Ak'],
index=[1, 2, 3, 4, 5, 6, 7, 8])
a = int(input("积分上界:"))
b = int(input("积分下界:"))
n = int(input("点数:"))
def f(x):
return x**2 * np.cos(x)
x, k = table.iloc[n-1, [0, 1]]
I = 0
for i in range(0, math.ceil(n/2)):
if x[i] != 0:
I = I + (f(x[i])+f(-x[i])) * k[i]
else:
I = I + f(x[i]) * k[i]
I = I*(a-b)/2
print('\n' + "高斯积分计算结果" + str(I))
- 测试结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210403205535935.png)