简体   繁体   English

python:math.sqrt(x)函数有多准确?

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

Consider the following code snippet in Python: 请考虑Python中的以下代码片段:

m = int(math.sqrt(n))

For n = 25, it should give m = 5 (and it does in my shell). 对于n = 25,它应该给出m = 5(并且它在我的shell中)。 But from my C experience I know that using such expression is a bad idea, as sqrt function may return a slightly lower value than the real value, and then after rounding i may get m = 4 instead of m = 5. Is this limitation also involved in python? 但是根据我的C经验,我知道使用这样的表达式是一个坏主意,因为sqrt函数可能返回比实际值稍低的值,然后在舍入后我可能得到m = 4而不是m = 5.这个限制是否也是参与python? And if this is the case, what is be the best way to write such expressions in python? 如果是这种情况,那么在python中编写这样的表达式的最佳方法是什么? What will happen if I use Java or C#? 如果我使用Java或C#会发生什么? Besides, if there is any inaccuracy, what factors controls the amount of it? 此外,如果有任何不准确之处,有哪些因素可以控制它的数量?

For proper rounding, use round() ; 为了正确的舍入,使用round() ; it rounds to the nearest whole number, but returns a float. 它舍入到最接近的整数,但返回一个浮点数。 Then you may construct an int from the result. 然后你可以从结果中构造一个int

(Most probably your code is not performance-critical and you will never notice any slowdown associated with round() . If you do, you probably should be using numpy anyway.) (很可能你的代码不是性能关键的,你永远不会注意到与round()相关的任何减速。如果你这样做,你可能应该使用numpy。)

If you are very concerned with the accuracy of sqrt , you could use the decimal.Decimal class from the standard library, which provides its own sqrt function. 如果您非常关心sqrt的准确性,可以使用标准库中的decimal.Decimal类 ,它提供自己的sqrt函数。 The Decimal class can be set to greater precision than regular Python float s. Decimal类可以设置为比常规Python float更高的精度。 That said, it may not matter if you are rounding anyways. 也就是说,如果你正在进行四舍五入也许并不重要。 The Decimal class results in exact numbers (from the docs): 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. 在十进制浮点数中, 0.1 + 0.1 + 0.1 - 0.3正好等于零。 In binary floating point, the result is 5.5511151231257827e-017 . 在二进制浮点数中,结果为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. 因此,在具有严格相等不变量的会计应用程序中,decimal是首选。

The solution is easy. 解决方案很简单。 If you're expecting an integer result, use int(math.sqrt(n)+.1). 如果您期望整数结果,请使用int(math.sqrt(n)+。1)。 If the value is a little more or less than the integer result, it will round to the correct value. 如果该值略大于或小于整数结果,则它将舍入到正确的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM