Sublime 2一直在崩溃?我的python代码有什么问题?

时间:2014-10-26 19:22:04

标签: python macos sublimetext2

我正在学习python,但这段代码不断崩溃我的文本编辑器。

谁能告诉我我做错了什么?

x = 12
epsilon = 0.01
numGuesses = 0
low = 0.0
high = max(1.0, x)
ans = (high + low)/2.0

while abs (ans**2 - x) >= epsilon:
    print 'low =', low, 'high =', high, 'ans =', ans
    numGuesses += 1
    if ans**2 < x:
        low = ans
    else:
        high - ans
    ans = (high + low)/2.0

print 'numGuesses =', numGuesses

print ans, 'is close to square root of', x

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

应改为:

x = 12
epsilon = 0.01
numGuesses = 0
low = 0.0
high = max(1.0, x)
ans = (high + low)/2.0

while abs (ans**2 - x) >= epsilon:
    print 'low =', low, 'high =', high, 'ans =', ans
    numGuesses += 1
    if ans**2 < x:
        low = ans
    else:
        high = ans
    ans = (high + low)/2.0

print 'numGuesses =', numGuesses

print ans, 'is close to square root of', x

答案如下:

low = 0.0 high = 12 ans = 6.0
low = 0.0 high = 6.0 ans = 3.0
low = 3.0 high = 6.0 ans = 4.5
low = 3.0 high = 4.5 ans = 3.75
low = 3.0 high = 3.75 ans = 3.375
low = 3.375 high = 3.75 ans = 3.5625
low = 3.375 high = 3.5625 ans = 3.46875
low = 3.375 high = 3.46875 ans = 3.421875
low = 3.421875 high = 3.46875 ans = 3.4453125
low = 3.4453125 high = 3.46875 ans = 3.45703125
numGuesses = 10
3.462890625 is close to square root of 12

答案 1 :(得分:1)

你处于无休止的while循环中。当你看看这个部分时:

while abs(ans**2 - x) >= epsilon:

while abs(ans**2 - x)总是提供24,而epsilon设置为0.01。

学习编程时,循环很棘手。它们将使您的处理器保持忙碌,直到您强制中止它们为止。这也是崩溃文本编辑器的原因。