As a Mathematician I would like:
Stephen Montgomery-Smith
stephen at math.missouri.edu
Fri Jun 29 13:34:56 PDT 2007
Don Clugston wrote:
>> 2. a%b has a very definite and unambiguous meaning when a is negative,
>> and b is positive. The output should be non-negative. This is
>> something perl has done right. For example (-6)%7 is 1.
>
> Unfortunately, in the floating-point world, that causes total loss of
> precision for small negative numbers. With the Perl definition,
> (-1e-50)%7 == 7. Also (-1e-80)%7=7.
> Consequently, x%7 - y%7 could be zero, even when x is totally different
> to y.
> That wrecks a lot of very nice algorithms.
> It's done this way for a reason.
It would be nice to know what algorithms the perl definition wrecks.
The kind of applications I am thinking of are things like calculating
the day of the week. So if you assign numbers like 0=Sunday, 1=Monday,
etc, and today is Sunday, what is the day of the week in x days time?
It is x%7. I want this to work even if x is negative (i.e. -x days ago).
Typically a%b is only used when a and b are integers, and then you don't
get floating point precision problems.
When a and b are not integers - well mathematically a%b represents an
equivalence class rather than a number. So a%b and (a+b)%b
mathematically should always be the same. So having(-1e-50)%7 = 7 is
really a problem with floating point arithmetic, not a problem with the
definition. If you have an application in which (-1e-50)%7 - (-1e-80)%7
= 0 messes you up, it seems to me that is an inherent problem with the
algorithm.
One place where mathematicians use a%b when a and b are not integers is
when b=2pi. (This is used when evaluating trig functions.) Since pi is
not an exact number anyway, the above issue should not be a problem.
For example, if you are applying the % operator to get your number
between -pi and pi before computing the sin function, you perhaps
shouldn't be using % anyway. Or rather, since this use is so embedded
in some other code that is already super complex, you might rather use
code that first tests if your number is small and negative before
applying %.
Whereas with my day of the week example, it would typically be part of
some really slick piece of code where making the correction will make it
super ugly.
Or to put it another way, when a is an integer, I really would like
a%256 to be the same as a&(0xff), which it will be even if a is negative
(assuming we are using 2's complement).
Stephen
More information about the Digitalmars-d
mailing list