Could we have mod in std.math?

Don nospam at nospam.com
Tue Dec 20 23:40:29 PST 2011


On 21.12.2011 07:08, Caligo wrote:
> 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?

Those names and semantics all come from C. We can't change them without 
an extremely good reason.
Note that things are a bit more complicated than you describe -- there 
is also the IEEE754 remainder function, which is really wierd.

A mod() function might not be a bad idea.




More information about the Digitalmars-d mailing list