floor() function definition

Tim Peters tim.one at home.com
Wed May 16 01:07:46 EDT 2001


[Dennis E. Hamilton]
> ...
> One fascinating identify for these functions is that
>
> 	ceil(x) = -floor(-x)
>
> and, of course, vice versa.

Here's a geometric explanation that some people find helpful:  picture x as a
point on a conventional "number line", with posts sticking out of the
integers.  If you're sitting on a post you're done.  Else for the floor move
to the left until hitting a fence, and for the ceiling move to the right.
That's it!  ceil(x) = -floor(-x) then follows from the relationship between
negation and reflection around 0.

> The Python real-number versions of these functions are very
> interesting for a way they can fail.  When x is too large in magnitude
> to be an exact integer, the result is an approximation in precisely
> the same way.

Every machine float of sufficiently large magnitude, with the sole exception
of +-infinity, *is* an exact integer.  Think about it:  every representable
finite non-zero float is of the form

    M * B**E

for some exact integers M, B and E, where B is usually fixed at 2, and if
there are P bits of precision then B**(P-1) <= abs(M) < B**P.  But every
number of that form is obviously an exact integer whenever E >= 0:  there is
no "fraction part" then, therefore it's an integer.  So floor() and ceiling()
return "large" floats unchanged, because they're exact integers already.

> There's not much that can be done about that, but it is odd.

Nope:  there's nothing surprising about floor() and ceiling() returning
integers unchanged.  What may be surprising is that all large floats *are*
integers; but that's not the fault of the floor/ceil functions, it's a
necessary and immediate consequence of the machine representation.

> I find myself uncomfortable about it, because there are key
> mathematical identities that fail at the boundary when x becomes
> too large in magnitude to be safely considered to be an integer.

ceil(x) = -floor(-x) holds in IEEE-754 arithmetic for every non-zero float,
including +-Infinity.

> ...
> Just the same, my inclination would be to raise an exception once
> floor(x) and ceil(x) can't be delivered as precise integers.

Python already does, but since there's no such case it's hard to notice the
absence of exceptions due to them <wink>.





More information about the Python-list mailing list