Hacker News new | past | comments | ask | show | jobs | submit login

This used to be unspecified behavior. C99 then codified this wrong behavior.

Assume positive b for a moment. We want a * (a/b) + (a%b) = a. If a%b is to always be within [0..b), then a/b has to round toward -infinity. C99 instead chose round towards 0.




That's right. Why do you suppose they chose that behavior to standardize, rather than Python's? Conceivably it's because nobody on the C99 standards committee had enough technical expertise to make the argument you're making, but can you think of another explanation? Because the prior probability on that one is pretty low.


> In C89, division of integers involving negative operands could round upward or downward in an implementation-defined manner; the intent was to avoid incurring overhead in run-time code to check for special cases and enforce specific behavior. In Fortran, however, the result will always truncate toward zero, and the overhead seems to be acceptable to the numeric programming community. Therefore, C99 now requires similar behavior, which should facilitate porting of code from Fortran to C.

Source: C99 Rationale v5.10 sec. 6.5.5p10 (http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10...)


Thanks for that. Now can anyone tell us where the Fortran behaviour came from?

(Haskell has both kinds of integer division, called div and quot, which is nice.)


Don't you mean we want "(a/b) + (a%b) = a"?


> We want a * (a/b) + (a%b) = a.

> Don't you mean we want "(a/b) + (a%b) = a"?

No, they mean "b * (a/b) + (a%b) = a". (Also I'm not convinced that's actually useful, but that's a different discussion.)


Ha - you’re correct of course. I saw the a^2 term and thought that can’t be right. Note to self - before attempting to correct others, check the “correction”.


> Don't you mean we want "(a/b) + (a%b) = a"?

Like, 1000/1000 + 1000%1000 = 1000? That sounds like undesirable behavior for division to me.


As others have pointed out, I did mean b*(a/b) here.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: