我有以下任务: Si(x) = sin(t)/t 从 0 到 x 的积分。编写一个接受参数 x 并返回 x 的正弦积分的 Python 代码。我不知道如何继续使用我的代码以使其正常工作。谁能帮我?
我收到此错误:
Traceback (most recent call last):
File "C:\Users\krist_000\Desktop\integration_simpson.py", line 37, in <module>
print(simpsons_rule( f_of_t, 2, b, N))
File "C:\Users\krist_000\Desktop\integration_simpson.py", line 18, in simpsons_rule
I += f(t) + (2.0*f(t+h) )
UnboundLocalError: local variable 't' referenced before assignment
[Finished in 0.1s with exit code 1]
这是我的代码:
def simpsons_rule( f, x, b, N):
*""" Implements simpsons_rule
f(t) - function to integrate
x - start point
b - end point
N - number of intervals, must be even.
"""*
if N & 1:
print ("Error: N is not a even number.")
return 0.0
h = (b - x) / N
I = 0.0
x = float(x)
for i in range(0, N/2):
I += f(t) + (2.0*f(t+h) )
t += 2*h
I = (2.0 * I) - f(x) + f(b)
I = h * I / 3.0
return I
import math
def f_of_t(t):
return (math.sin(t)) / t
N = 1000
b = 0.0
print(simpsons_rule( f_of_t, 2, b, N))