玩蛇网提供最新Python编程技术信息以及Python资源下载!
您现在的位置: 玩蛇网首页 > Python问题解答 > 正文内容

Python源码问题算负数平方根无结果输出何解

def findRoot(x, power, epsilon):
    """Assumes x and epsilon int or float, power an int,
           epsilon > 0 & power >= 1
       Returns float y such that y**power is within epsilon of x.
           If such a float does not exist, it returns None"""
##    if x < 0 and power%2 == 0:
##        return None
    low = min(-1.0, x)
    high = max(1.0, x)
    ans = (high + low)/2.0
    while abs(ans**power - x) >= epsilon:
        if ans**power < x:
            low = ans
        else:
            high = ans
        ans = (high + low)/2.0
    return ans

def testFindRoot():
    epsilon = 0.0001
    for x in (0.25, -0.25):
        for power in range(1, 4):
            print 'Testing x = ' + str(x) +\
                  ' and power = ' + str(power)
            result = findRoot(x, power, epsilon)
            if result == None:
                print '    No root'
            else:
                print '   ', result**power, '~=', x

没有注释掉

if x < 0 and power%2 == 0:
    return None

之前输出正常:

Testing x = 0.25 and power = 1
    0.25 ~= 0.25 
Testing x = 0.25 and power = 2
    0.25 ~= 0.25
Testing x = 0.25 and power = 3
    0.249907490797 ~= 0.25
Testing x = -0.25 and power = 1
    -0.25 ~= -0.25
Testing x = -0.25 and power = 2
    No root 
Testing x = -0.25 and power = 3
    -0.249907490797 ~= -0.25

注释掉以后到Testing x = -0.25 and power = 2下边就没往下走了,而且程序也没有退出然后出现shell提示符>>>,为什么这里不是继续输出0 ~= -0.25或其他呢?

那个while循环里,low = high = ans = -1.0,死循环了,所以没有输出结果。

玩蛇网文章,转载请注明出处和文章网址:http://www.iplaypy.com/wenda/wd18598.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2017年05月31日 - 11时31分22秒 发布自玩蛇网

我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules