使用SymPy,递归函数返回“None”值

时间:2021-11-29 01:42:42
from sympy import *

x = Symbol('x')

f = (2*x) + 1

fprime = f.diff()

f = lambdify(x, f)
fprime = lambdify(x, fprime)
newtons_expr = lambdify(x, x - (f(x) / fprime(x)) )


def newtons_method(guess):

    approx = newtons_expr(guess)

    if Abs(approx - guess) < 0.001:
        print(approx) # <-- returns a float (-0.5)
        print(type(approx)) # <-- returns "<class 'float'>"
        return approx # <-- returns a None
    else:
        newtons_method(approx)

print(newtons_method(1))

I built this function using SymPy to evaluate one of the solutions to an equation using Newton's method. For some reason, however, its returning a None instead of a float, even though it explicitly prints a float before it returns the value of approx. What's wrong here? I've never seen this before.

我使用SymPy构建了这个函数,使用牛顿方法评估方程的一个解。但是,出于某种原因,它返回一个None而不是float,即使它在返回值大约之前显式地打印了一个浮点数。这有什么不对?我以前从未见过这个。

1 个解决方案

#1


0  

Thanks @PaulRooney!

谢谢@PaulRooney!

My mistake was was here:

我的错误在于:

else:
    newtons_method(approx)

When you're calling a recursive function, you need to have it return itself every call; otherwise, it will return None. It should've been:

当你调用一个递归函数时,你需要让它在每次调用时返回它自己;否则,它将返回None。应该是:

else:
    return newtons_method(approx)

I found this video explaining the "call stack" Paul mentions in our discussion. I watched it and it gave me some insight as to what my function was doing logically: https://www.youtube.com/watch?v=k0bb7UYy0pY

我发现这段视频解释了Paul在我们的讨论中提到的“调用堆栈”。我看了它,它给了我一些关于我的功能在逻辑上做什么的见解:https://www.youtube.com/watch?v = k0bb7UYy0pY

#1


0  

Thanks @PaulRooney!

谢谢@PaulRooney!

My mistake was was here:

我的错误在于:

else:
    newtons_method(approx)

When you're calling a recursive function, you need to have it return itself every call; otherwise, it will return None. It should've been:

当你调用一个递归函数时,你需要让它在每次调用时返回它自己;否则,它将返回None。应该是:

else:
    return newtons_method(approx)

I found this video explaining the "call stack" Paul mentions in our discussion. I watched it and it gave me some insight as to what my function was doing logically: https://www.youtube.com/watch?v=k0bb7UYy0pY

我发现这段视频解释了Paul在我们的讨论中提到的“调用堆栈”。我看了它,它给了我一些关于我的功能在逻辑上做什么的见解:https://www.youtube.com/watch?v = k0bb7UYy0pY