Python 函数两次返回第一个值

Python function returning first value twice

我已经编写了这个函数来使用泰勒级数计算 sin(x) 到任何指定的准确度,'N terms',我的问题是结果没有按预期返回,我不能找出原因,任何帮助将不胜感激。

我期待的是: 1 6.28318530718 2 -35.0585169332 3 46.5467323429 4 -30.1591274102 5 11.8995665347 6 -3.19507604213 7 0.624876542716 8 -0.0932457590621 9 0.0109834031461

我得到的是: 1 None 2 6.28318530718 3 -35.0585169332 4 46.5467323429 5 -30.1591274102 6 11.8995665347 7 -3.19507604213 8 0.624876542716 9 -0.0932457590621

提前致谢。

def factorial(x):
    if x <= 1:
        return 1
    else:
        return x * factorial(x-1)

def sinNterms(x, N):
    x = float(x)

    while N >1:
        result = x
        for i in range(2, N):
            power = ((2 * i)-1)
            sign = 1
            if i % 2 == 0:
                sign = -1
            else:
                sign = 1
            result = result + (((x ** power)*sign) / factorial(power))
        return result

pi = 3.141592653589793
for i in range(1,10):
    print i, sinNterms(2*pi, i)

我看到您将 return 放在 for 下,这将使它脱离 while 循环。您应该解释这是否是您的意思。但是,鉴于 for i in range(1,10): 意味着当输入参数 i 为 1 时,您将忽略第一个条目和 return None。这真的是您想要的吗?另外,因为你总是在计算后退出,你不应该做 while N > 1 而是使用 if N > 1 来避免无限递归。

您的结果不正确的原因是您使用的范围不正确。 range(2, N) 为您提供来自 2 to N-1 的数字列表。因此 range(2, 2) 给你一个空列表。

你应该计算 range(2, N+1)

def sinNterms(x, N):
    x = float(x)

    while N >1:
        result = x
        for i in range(2, N):

您的评论说明您的代码行顺序错误。你应该

def sinNterms(x, N):
    x = float(x)

    result = x
    # replace the while with an if since you do not need a loop
    # Otherwise you would get an infinite recursion
    if N > 1:
        for i in range(2, N+1):
            power = ((2 * i)-1)
            sign = 1
            if i % 2 == 0:
                sign = -1
            # The else is not needed as this is the default
            # else:
            #     sign = 1
            # use += operator for the calculation
            result += (((x ** power)*sign) / factorial(power))
    # Now return the value with the indentation under the if N > 1
    return result

请注意,为了处理事情,请将阶乘设置为 return 浮点数而不是整数。

另一种可以节省一些计算的方法是

def sinNterms(x, N):
    x = float(x)
    lim = 1e-12
    result = 0
    sign = 1
    # This range gives the odd numbers, saves calculation.
    for i in range(1, 2*(N+1), 2):
        # use += operator for the calculation
        temp = ((x ** i)*sign) / factorial(i)
        if fabs(temp) < lim:
            break
        result += temp
        sign *= -1
    return result