modulus redux

Don nospam at nospam.com
Mon Jul 13 00:28:53 PDT 2009


Andrei Alexandrescu wrote:
> Ok, here's how I rewrote the section on multiplicative operations. The 
> text is hardly intelligible due to all formatting, sorry about that (but 
> it looks much better in a specialized editor). Comments and suggestions 
> welcome.
> 
> \subsection{Multiplicative Expressions}
> 
> The  multiplicative expressions  are multiplication  (\ccbox{a  * b}),
> division  (\ccbox{a  / b}),  and  remainder  (\ccbox{a  \% b}).   They
> operate  on numeric types  only. The  result type  of either  of these
> operations   is  same  as   the  type   of  \ccbox{true   ?  a   :  b}
> (see~\S~\ref{sec:conditional-operator}).
> 
> If~@b@ is zero in the integral  operation \ccbox{a / b} or \ccbox{a \%
>    b}, a hardware  exception is thrown. If the  division would yield a
> fractional number,  it is always truncated towards  zero (for example,
> \ccbox{7  /  3}  yields~@2@  and  \ccbox{-7 /  3}  yields~@-2@).   The
> expression \ccbox{a \% b} is defined such  that \cc{a == (a / b) * b +
>    a  \%  b},  so  \ccbox{7  \%  3}  yields~@1@  and  \ccbox{-7  /  3}
> yields~@-1 at .
> 
> \dee also  defines modulus for floating-point  numbers. The definition
> is more involved. When at least one of @a@ and @b@ is a floating-point
> value in  \cc{a \% b}, the  result is the largest  (in absolute value)
> floating-point number @r@ satisfying the following conditions:
> 
> \begin{itemize*}
> \item @a@ and @r@ do not have opposite signs;
> \item  @r@ is  smaller than  @b@  in absolute  value, \ccbox{abs(r)  <
>      abs(b)};
> \item there exists a number @q@ of type @long@ such that \ccbox{r == a
>      - q * b}.
> \end{itemize*}
> 
> If such  a number  cannot be found,  \ccbox{a \%  b} yields the  Not A
> Number (NaN) special value.
> 
> 
> Andrei

Close, but that's technically not true in the case where abs(a/b) > 
long.max. (The integer doesn't have to fit into a 'long').

In IEEE754, r= a % b is defined by the mathematical relation r = a  – b 
  * n , where n is the integer nearest the exact number a/b ; whenever 
abs( n  – a/b) = 0.5 , then n is even. If r == 0 , its sign is the same 
as a.



More information about the Digitalmars-d mailing list