【发布时间】:2018-01-23 15:15:42
【问题描述】:
我正在研究 Guttag 书中的一个程序,专门修改第 33 页的代码以使用负数。该程序试图通过使用二分搜索来找到一个数字的平方根。
简而言之我的问题:
>>> print(ans)
-12.0
>>> print(ans**2)
144.0
>>> print(-12**2)
-144
>>> -12.0**2
-144.0
对一个数字(在本例中为 -12)进行平方得到了我在将 IDLE 作为数字放入时所期望的正确答案。然而,当它来自一个变量时,它突然变为正数。知道为什么会发生这种情况以及如何解决吗?
我在较长版本中的问题,以防我也理解了其他错误:
x = float(input("Enter an integer, which square root you want to find: "))
epsilon = 0.01
numGuesses = 0
low = min(0.0, x)
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("Number of guesses =", numGuesses)
print(ans, "is close to square root of", x)
因此,当 while 循环决定是否将变量 ans 分配给 high 或 low 时,如果从一开始就使用负数,它就不能这样做。例如,如果我用 x = -25 运行这个程序,它将打印出以下内容:
Enter an integer, which square root you want to find: -25
low = -25.0 high = 1.0 ans = -12.0
low = -25.0 high = -12.0 ans = -18.5
虽然 ans (-12) squared 应该是 -144,但这会将其分配给“低”而不是高,并使程序正常工作。
感谢所有建议。
【问题讨论】:
-
运算符优先级。
-12**2表示-(12**2)。使用(-12)**2。 -
对负数进行平方应该产生正结果,而不是负数。为什么你认为
-144是正确的?
标签: python variables negative-number