years later DeprecationWarning

Steven D'Aprano steve at
Sun Mar 26 03:00:57 CEST 2006

On Wed, 22 Mar 2006 13:59:00 -0800, Chris Lasher wrote:

> Two things:
> 1) math.floor returns a float, not an int. Doing an int() conversion on
> a float already floors the value, anyways.

No it doesn't, or rather, int() is only equivalent to floor() if you limit
the input to non-negative numbers:

int(-2.2) => -2, but floor(-2.2) should give -3.

The standard definition of floor() and ceil() are:

floor(x) = maximum integer n such that n <= x
ceil(x) = minimum integer n such that n >= x

or as Python functions:

def floor(x):
    "Returns the maximum integer less than or equal to x"
    if x >= 0:
        return int(x)
        if x % 1: return int(x)-1
        else: return int(x)

def ceil(x):
    "Returns the minimum integer greater than or equal to x"
    return -floor(-x)

or even simpler:

from math import floor, ceil

(Caution: the functions defined in the math module return the floor and
ceiling as floats, not int, so you may want to wrap them in a call to int.)


More information about the Python-list mailing list