简体   繁体   English

Sublime2一直崩溃? 我的python代码有什么问题?

[英]Sublime2 keeps crashing? What is wrong with my python code?

I'm learning python, but this code keeps crashing my text editor. 我正在学习python,但是这段代码不断使我的文本编辑器崩溃。

Can anyone tell me what I'm doing wrong? 谁能告诉我我在做什么错?

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

Any suggestions? 有什么建议么?

Should be this instead: 应该是这样的:

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

Answer look like this: 答案看起来像这样:

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

You are in an endless while -loop. 您处于无尽的while循环中。 When you have a look at this part: 当您查看此部分时:

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

while abs(ans**2 - x) always gives 24, while epsilon is set to 0.01. while abs(ans**2 - x)始终为24,而epsilon设置为0.01。

When learning to program, while loops are tricky. 在学习编程时,while循环很棘手。 They will keep your processor busy until you forcefully abort them. 它们将使您的处理器处于繁忙状态,直到您强行中止它们。 This is also what has been crashing your text editor. 这也是导致文本编辑器崩溃的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM