Reputation: 4600
Consider the following code snippet in Python:
m = int(math.sqrt(n))
For n = 25, it should give m = 5 (and it does in my 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? And if this is the case, what is be the best way to write such expressions in python? What will happen if I use Java or C#? Besides, if there is any inaccuracy, what factors controls the amount of it?
Upvotes: 3
Views: 1922
Reputation: 40894
For proper rounding, use round()
; it rounds to the nearest whole number, but returns a float. Then you may construct an int
from the result.
(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.)
Upvotes: 7
Reputation: 17096
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. The Decimal
class can be set to greater precision than regular Python float
s. That said, it may not matter if you are rounding anyways. The Decimal
class results in exact numbers (from the docs):
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 is5.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.
Upvotes: 3
Reputation: 7946
The solution is easy. If you're expecting an integer result, use 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.
Upvotes: 2