Whos idea was to make integer division round towards 0? -.-

Started by
10 comments, last by wintertime 11 years, 3 months ago

Now i have to make a function for division where it always rounds down, since i dont care about the sign, i just want the origin to be 0 :c

Discuss

o3o

Advertisement

Maybe it's wired that way.

Maybe it's wired that way.

And because of that it will never be changed and will continue to annoy people who assume it to always round down because it feels logical in this context. :C

o3o

I never found it to be a very big issue.

http://en.cppreference.com/w/cpp/numeric/math/floor

To answer the actual question ("Whose idea was it..."), that would be William James Cody, with contributions of half a dozen people from IBM, Apple, and the University of Berkeley.
http://en.cppreference.com/w/cpp/numeric/math/floor

Actually i didnt end up using that because its the rounding after division, what i do is check if the signs of a and b are different and if yes i subtract 1.

The reason why this caused problems was that i was treating the integer just like it wasnt signed (for coordinates on a map, i had the precise coord and had to divide to get the chunk coord), which caused problems with the rounding direction changing at the origin, making the 0 chunk twice bigger than the other ones.

o3o

Because it's not rounding, it's truncating. Rounding wouldn't really be appropriate in this context and, in my opinion at least, it would be so much more annoying for it to round by default and necessitate special functionality to truncate instead.

Yeah, it's called truncating.

If you're always dividing by a power of two, you can use arithmetic bitshifts, they always round down (floor).

Alternatively, you can use this function for flooring arbitrary denominators:

inline int floor_div(int a_numerator, int a_denominator)
{
return (a_numerator / a_denominator) + ((a_numerator % a_denominator) >> 31);
}

If integer division didn't round towards zero, it would be inconsistent with the mathematical definition of integer division, and a lot of number theoretical code would have weird +1's and -1's everywhere, which sucks. I like it the way it is, and it's never gotten in my way.

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”

This topic is closed to new replies.

Advertisement