为了账号安全,请及时绑定邮箱和手机立即绑定

Python算负数平方根没有输出

Python算负数平方根没有输出

MMTTMM 2019-02-21 09:47:33
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或其他呢?
查看完整描述

1 回答

?
慕后森

TA贡献1802条经验 获得超5个赞

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

查看完整回答
反对 回复 2019-03-01
  • 1 回答
  • 0 关注
  • 847 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信