我有以下赋值:Si(x)= sin(t)/ t从0到x的积分。编写一个python代码,它接受参数x并返回该x的正弦积分。 我无法弄清楚如何继续使用我的代码来使其工作。任何人都可以帮助我吗?
我收到此错误:
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))
答案 0 :(得分:0)
PyCharm发现你的代码存在一些问题。您的代码现在编译并运行。根据{{3}}:
,我得到了正确的答案F:\Tools\python-2.7.3\python.exe F:/Projects/Python/udacity/udacity/simpsons.py
1.6054029768
Process finished with exit code 0
看看这对你有效。你应该好好研究我所做的改变,并理解我为什么做出这些改变:
def simpsons_rule(f, a, b, n):
"""
Implements simpsons_rule
:param f: function to integrate
:param a: start point
:param b: end point
:param n: number of intervals, must be even.
:return: integral of the function
"""
if n & 1:
print ("Error: n is not a even number.")
return 0.0
h = float(b - a) / n
integral = 0.0
x = float(a)
for i in range(0, n / 2):
integral += f(x) + (2.0 * f(x + h))
x += 2 * h
integral = (2.0 * integral) - f(a) + f(b)
integral = h * integral / 3.0
return integral
import math
def f_of_t(t):
# Note: guard against singular behavior at t = 0.
# L'Hospital says value should be 1.0. NAN if you don't check.
if x == 0:
return 1.0
else:
return (math.sin(t)) / t
n = 10000
a = 0
b = 2
print(simpsons_rule(f_of_t, a, b, n))