Re: [Algorithms] Converting floats to a specific range
Brought to you by:
vexxed72
From: Fabian G. <ry...@gm...> - 2010-05-07 15:28:33
|
On 07.05.2010 14:35, Danny Kodicek wrote: > A quick unlurk - I've often wondered why mod functions always seem to do > this. Can anyone explain that? I can think of very few occasions when > you want to take the mod of a number and not restrict it to a single > range, rather than maintaining the positive or negative value. I > understand that doing it this way makes the function faster, but given > that you usually have to override it anyway that would seem a bit of a > meaningless saving. It has to do with the rounding semantics of division. The basic requirement they're trying to fulfill is that if q = a / b; r = a % b; then a should be equal to "q * b + r" (all sensible, so far). Now, C doesn't actually specify what (integer) division does when diving a negative number by a positive one. The two primary options are truncate (round towards zero) and floor (always round down). If the target platform has "floor" semantics, then r is always nonnegative, and e.g. "-1 / 2" evaluates to -1 (this is also the behavior you get when you replace divisions by powers of two with arithmetic right shifts). If the target platform has "truncate" semantics, "-1 / 2" evaluates to 0, and hence the remainder has to be -1. All platforms I've worked with so far use this convention, even though it's (as said) not required by the C standard - floor would be equally fine. Interestingly, the C standard does seem to specify that fmod returns results as if a truncate-rounding division was used. It's only left undefined for integer operations. -Fabian |