python 中的平方根算法

Square root algorithm in python

我在 python 中使用 while 循环执行此操作。它没有终止。

x = 2.0
ans = 0
while ans**2 != abs(x):    
    print (ans)  
    ans = ans + 0.001
    if ans**2 == abs(x):  
        print(ans)

您不应该使用 !=== 运算符来比较浮点变量,因为使用这种幼稚的算法您不可能达到精确的平方根。相反,您应该定义您愿意容忍的可接受错误并继续,直到您找到一个错误小于该错误的数字。然而,then 可能还不够。由于你有一个恒定的增量,你很可能会发现你永远不会足够接近你正在搜索的平方根,因此,需要额外的保护措施来不通过所需的结果并继续无穷大:

x = 2.0
ans = 0
step = 0.001
delta = 0.0001
while ans**2 < x and abs (ans**2 - x) > delta:
    ans = ans + step

# Done looping, found the best ans for ans**2<x.
# Check one additional value where ans**2>x 
# and choose the one with the smaller delta

overAns = ans + step
if abs (overAns ** 2 - x) < abs (ans ** 2 - x):
    print overAns
else:
    print ans 

即使这样也不能像您希望的那样工作:

>>> (2 ** 0.5) ** 2 == 2
False

不过,对于某些数字,即使对于非正方形也是如此:

>>> (11 ** 0.5) ** 2 == 11
True

更简单的计算甚至会出错:

>>> 0.1 + 0.2 == 0.3
False

问题是,一般来说,计算机并不能准确地表示浮点数。您只会得到一个接近正确数字的数字。因此,您不应该进行精确性测试,而应该进行接近性测试(检查差异是否小于足以满足您需求的小数)。

>>> abs((2 ** 0.5) ** 2 - 2) < 1e-10
True