我试图编写一个近似平方根的函数(我知道有数学模块......我想自己做),我被浮点运算搞砸了.你怎么能避免这种情况?
def sqrt(num):
root = 0.0
while root * root < num:
root += 0.01
return root
Run Code Online (Sandbox Code Playgroud)
使用它有以下结果:
>>> sqrt(4)
2.0000000000000013
>>> sqrt(9)
3.00999999999998
Run Code Online (Sandbox Code Playgroud)
我意识到我可以使用round(),但我希望能够让它真正准确.我希望能够计算出6或7位数.如果我四舍五入,这是不可能的.我想了解如何在Python中正确处理浮点计算.