2014-10-26 83 views
-1

我正在学习python,但是这段代码不断崩溃我的文本编辑器。Sublime2不断崩溃?我的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 

有什么建议吗?

+1

高= ans而不是高-ans – lakesh 2014-10-26 19:27:20

+1

这段代码肯定与编辑器崩溃无关。如果是这样,这将是脱离主题,并将属于superuser.com – 2014-10-26 19:29:45

回答

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

您在无尽的while -loop。当你看看这一部分:

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

while abs(ans**2 - x)总是给人24,而epsilon设为0.01。

学习编程时,while循环很棘手。他们会让你的处理器很忙,直到你强制中止它们。这也是你的文本编辑器崩溃的原因。