1

我有以下任务: 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))
4

1 回答 1

0

PyCharm 发现您的代码存在一些问题。您的代码现在编译并运行。根据Wolfram Alpha的说法,我得到了正确的答案:

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))
于 2013-04-29T09:49:28.270 回答