views:

160

answers:

3

Hi,

Python's math module contain handy functions like floor & ceil. These functions take a floating point number and return the nearest integer bellow or above it. However these functions return the answer as a floating point number. For example:

In [1]: import math
In [2]: f=math.floor(2.3)
In [3]: f
Out[3]: 2.0

What is the safest way to get an integer out of this float, without running the risk of rounding errors (for example if the float is the equivalent of 1.99999... )? or perhaps I should use another function altogether?

Thanks, Boaz

+1  A: 

math.floor will always return an integer number and thus int(math.floor(some_float)) will never introduce rounding errors.

hop
+5  A: 

All integers that can be represented by floating point numbers have an exact representation. So you can safely use int on the result. Inexact representations occur only if you are trying to represent a rational number with a denominator that is not a power of two.

That this works is not trivial at all! It's a property of the IEEE floating point representation that int∘floor = ⌊⋅⌋ if the magnitude of the numbers in question is small enough, but different representations are possible where int(floor(2.3)) might be 1.

To quote from Wikipedia,

Any integer with absolute value less than or equal to 224 can be exactly represented in the single precision format, and any integer with absolute value less than or equal to 253 can be exactly represented in the double precision format.

Philipp
+1 for going a bit deeper. You could also throw in a brief explanation as to why: http://en.wikipedia.org/wiki/Floating_point :D
CrazyJugglerDrummer
A: 

You could use the round function. If you use no second parameter (# of significant digits) then I think you will get the behavior you want.

IDLE output.

>>> round(2.99999999999)
3
>>> round(2.6)
3
>>> round(2.5)
2
>>> round(2.4)
2
Wade73
`round` returns a float number as well, at least in Python 2.6.
Philipp
In Python 3.1.2, round returns an int.
robert
Indeed, both `round` and `floor` return integers in Python 3.x. So I suppose that the question concerns Python 2.x.
Philipp
and since (it appears that) the OP is using IPython which isn't available for py3k, that's probably a valid supposition, Phillip.
Wayne Werner