亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 856 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號