[Python-Dev] Floor division

Tim Peters tim.peters at gmail.com
Fri Jan 26 11:03:44 CET 2007


[Tim (misattributed to Guido)]
>> "(int)float_or_double" truncates in C (even in K&R C) /provided that/
>> the true result is representable as an int.  Else behavior is
>> undefined (may return -1, may cause a HW fault, ...).

[Nick Maclaren]
> Actually, I have used Cs that didn't, but haven't seen any in over
> 10 years.

I believe those.

> C90 is unclear about its intent,

But am skeptical of that.  I don't have a copy of C90 here, but before
I wrote that I checked Kernighan & Ritchie's seminal C book, Harbison
& Steele's generally excellent "C: A Reference Manual" (2nd ed), and a
web version of Plauger & Brodie's "Standard C":

     http://www-ccs.ucsd.edu/c/

They all agree that the Cs they describe (all of which predate C99)
convert floating to integral types via truncation, when possible.

> but C99 is specific that truncation is towards zero.

As opposed to what?  Truncation away from zero?  I read "truncation"
as implying toward 0, although the Plauger & Brodie source is explicit
about "the integer part of X, truncated toward zero" for the sake of
logic choppers ;-)

> This is safe, at least for now.

>> So Python uses C's modf() for float->int now, which is always defined
>> for finite floats, and also truncates.

> Yes.  And that is clearly documented and not currently likely to
> change, as far as I know.

I don't expect to see another C standard in my lifetime, given that
some major C compiler vendors still ignore C99 (and given that my
expected remaining lifetime is much less than that of most people
reading this ;-)).


More information about the Python-Dev mailing list