【问题标题】:Function not returning value (Python 2.7)函数不返回值(Python 2.7)
【发布时间】:2014-08-22 13:24:33
【问题描述】:

我正在尝试在 Python 2.7 中实现二分法函数。我真的很困惑为什么我的代码没有返回我在测试中括起来的根。

当我在代码中添加打印语句时,很明显算法正在寻找根,但我一定错过了实际语法中的一些基本内容(我是 python 的完全新手)。

代码在这里:

def bisection(a,b,fun,tol):
    c = (a+b)/2.0
    if (b-a)/2.0 <= tol:
        #Debugging print statement 1:
        #print 'SOL1: c = ', c
        return c

    if fun(c) == 0:
        #Debugging print statement 2:
        #print 'SOL2: c = ', c
        return c

    elif fun(a)*fun(c) < 0:
        b = c
    else:
        a = c
    print 'a =', a
    print 'b =', b
    bisection(a, b, fun, tol)

def tstr(x):
    return 2*(x**2) - 3*x + 1

sol = bisection(0, 0.9, tstr, 0.01)

【问题讨论】:

    标签: python python-2.7 return


    【解决方案1】:

    最后你忽略了递归调用;您确实需要显式返回其返回值:

    return bisection(a, b, fun, tol)
    

    这里不使用return意味着递归调用返回值被忽略,outer调用函数结束时没有明确的return花蕊,因此返回None

    通过这个更改,sol 实际被设置:

    >>> sol = bisection(0, 0.9, tstr, 0.01)
    a = 0.45
    b = 0.9
    a = 0.45
    b = 0.675
    a = 0.45
    b = 0.5625
    a = 0.45
    b = 0.50625
    a = 0.478125
    b = 0.50625
    a = 0.4921875
    b = 0.50625
    >>> sol
    0.49921875
    

    【讨论】:

      猜你喜欢
      • 2016-04-18
      • 2018-11-28
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多