关于C#:Python:math.sqrt(x)函数的精度如何?

python: how accurate math.sqrt(x) function is?

在Python中考虑以下代码片段:

1
m = int(math.sqrt(n))

对于n = 25,它应该给m = 5(并且在我的shell中确实如此)。但是从我的C经验中,我知道使用这样的表达式是一个坏主意,因为sqrt函数的返回值可能会比实际值稍低,然后在四舍五入后,我可能会得到m = 4而不是m = 5。参与python吗?如果是这种情况,用python编写此类表达式的最佳方法是什么?如果我使用Java或C#,会发生什么?
此外,如果有任何不准确之处,哪些因素控制着它的数量?


为正确舍入,请使用round();四舍五入到最接近的整数,但返回一个浮点数。然后您可以根据结果构造一个int

(很可能您的代码不是性能至关重要的对象,并且您永远不会注意到与round()相关的任何速度下降。如果这样做,您可能仍然应该使用numpy。)


如果您非常关心sqrt的准确性,则可以使用标准库中的decimal.Decimal类,该类提供了自己的sqrt函数。可以将Decimal类设置为比常规Python float更高的精度。也就是说,无论如何,四舍五入都可能无关紧要。 Decimal类产生精确的数字(来自文档):

The exactness [of Decimal] carries over into arithmetic. In decimal floating point,
0.1 + 0.1 + 0.1 - 0.3 is exactly equal to zero. In binary floating point, the result is 5.5511151231257827e-017. While near to zero, the
differences prevent reliable equality testing and differences can
accumulate. For this reason, decimal is preferred in accounting
applications which have strict equality invariants.


解决方案很简单。如果期望整数结果,请使用int(math.sqrt(n).1)。如果该值大于或小于整数结果,它将四舍五入为正确的值。