from sympy import * #科特斯系数计算函数 def C(n=int(), k=int()): if (n - k) % 2 == 0: ans = 1 else: ans = -1 for j in range(n+1): if j != k: ans *= (x - j) ans = integrate(ans, (x, 0, n)) / n for i in range(k): ans /= (i+1) for i in range(n-k): ans /= (i+1) print(ans, end=' ') def cotes_formula(a, b): h = (b - a) / 5 coefficient_list = [19, 25, 50, 50, 75,19] C = 0 for k in range(len(coefficient_list)): C = C + coefficient_list[k] * func(a + k * h) C = C * (b - a) / 288 return C # 积分函数 def func(x): return 1 / (1 + x ** 2) x = symbols('x') for i in range(8): for j in range(i+2): C(i+1, j) print() def newton_cotes_integral(f, a, b, n): step = (b - a) / n xs = [a + i * step for i in range(n+1)] return (b - a) * sum([C(n, k) * f(xs[k]) for k in range(0, n+1)]) a=-5 b=5 for i in range(1,51): print(newton_cotes_integral(func,a, b,i))给这段代码纠正错误
时间: 2023-12-26 08:06:03 浏览: 132
科特斯求积分
这段代码存在一些错误,我来帮你纠正一下:
1. 在调用 `C(i+1, j)` 函数时,没有传入参数 `x`,需要将其改为 `C(i+1, j, x)`。
2. 在函数 `cotes_formula` 中,`func(a + k * h)` 应该改为 `f(a + k * h)`。
3. 在函数 `newton_cotes_integral` 中,`C(n, k)` 应该改为 `C(n, k, x)`。
下面是修改后的代码:
```
from sympy import *
# 科特斯系数计算函数
def C(n=int(), k=int(), x=symbols('x')):
if (n - k) % 2 == 0:
ans = 1
else:
ans = -1
for j in range(n+1):
if j != k:
ans *= (x - j)
ans = integrate(ans, (x, 0, n)) / n
for i in range(k):
ans /= (i+1)
for i in range(n-k):
ans /= (i+1)
print(ans, end=' ')
def cotes_formula(f, a, b):
h = (b - a) / 5
coefficient_list = [19, 25, 50, 50, 25, 19]
C = 0
for k in range(len(coefficient_list)):
C = C + coefficient_list[k] * f(a + k * h)
C = C * (b - a) / 288
return C
# 积分函数
def func(x):
return 1 / (1 + x ** 2)
x = symbols('x')
for i in range(8):
for j in range(i+2):
C(i+1, j, x)
print()
def newton_cotes_integral(f, a, b, n):
step = (b - a) / n
xs = [a + i * step for i in range(n+1)]
return (b - a) * sum([C(n, k, x) * f(xs[k]) for k in range(0, n+1)])
a = -5
b = 5
for i in range(1,51):
print(newton_cotes_integral(func, a, b, i))
```
阅读全文