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或其他呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值