Could we have mod in std.math?

Caligo iteronvexor at gmail.com
Tue Dec 20 22:08:24 PST 2011


1.
The % operator, just like in C/C++, calculates the remainder, but it
doesn't handle negative numbers properly.  It's not a mod operator, even
though sometimes it's called that.

  assert(-6 %  20 == -6);
  assert( 6 % -20 ==  6);
  assert(-6 % -20 == -6);

I use my own mod function whenever I need to handle negative numbers.  It
looks like this:

pure T mod(T)(T n, T d) if(isIntegral!(T)){
  T r = n % d;
  return sgn(r) == -(sgn(d)) ? r + d : r;
}

  assert(mod(-6,  20) ==  14);
  assert(mod( 6, -20) == -14);
  assert(mod(-6, -20) == -6);

I'm hoping to see something like the above mod function in Phobos someday.
And perhapse a 'rem' or 'remainder' function that's a wrapper for the %
operator, just to stay consistent.

2.
With the above, the math.fmod then would have to be renamed to 'frem'
because, just like the % for integrals, it doesn't handle negative numbers
properly only calculates the remainder.

  assert(fmod(-6,  20) == -6);
  assert(fmod( 6, -20) ==  6);
  assert(fmod(-6, -20) == -6);

I'm not so sure why we have 're­main­der` and `remquo` in std.math when
there is 'fmod`, though.

What do you guys think?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20111221/5fad7c23/attachment.html>


More information about the Digitalmars-d mailing list