Live data from Hacker News

Why Python's integer division floors (2010)

python-history.blogspot.com

101–102 of 102 posts

Re: Why Python's integer division floors (2010)

#101
post #85

Earlier quoted context omitted.

However, the oposite shift is undefined if a 1 goes into the sign bit. More precisely, regarding E1 "If E1 has a signed type and nonnegative value, and E1 × 2ᴱ² is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined." Thus if E1 is negative, or if the result overflows, UB.

Didn't they specify two's complement signed integers somewhat recently? What's the rationale for leaving these behaviours undefined?

On some CPUs architectures, the operand size for some instructions could be larger than an `int`, in which case the upper part of a CPU register would become invalid on overflow instead of containing an extension of the sign bit.

There are also CPUs that do "saturating arithmetic" where overflow results in INT_MAX instead of wrapping.

Re: Why Python's integer division floors (2010)

#102
post #18
post #4

Earlier quoted context omitted.

I strongly disagree. I would estimate that in 90% of cases where I use modulo in languages that truncate (instead of flooring), I write (a % b + b) % b, or something similar, just to get the right behaviour. The exceptional cases are those where I can convince myself that negative numbers simply won't come up. (It's never because I actually want the other behaviour for negative numbers.) - When using modulo to access…

A common approach (e.g. Cobol, Ada, Common Lisp, Haskell, Clojure, MATLAB, Julia, Kotlin) seems to be to provide two operators: One that uses truncated division, one that uses floored division. By convention, rem truncates, and mod floors.

And first of all, Fortran.
Post reply on HN