lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On 23-Jan-06, at 10:05 AM, Roberto Ierusalimschy wrote:

No. 2^i always needs just a single bit of precision in the
mantissa. Only the exponent changes.

This is only true if you know the number is a power of 2. (But then you
don't even need the number, only the power. And you don't need to call
fmod either). If you are handling numbers in general, 2^i needs all its
zeros in the mantissa to tell it apart from 2^i + delta.

The point is that if x and y are both exactly representable, then fmod(x, y) gives the exact correct result (at least, correct in the sense of the definition of fmod, which I agree is a bizarre definition). That is a useful property.

With respect to speed:

1) William Kahan, "The Baleful Effect of Computer Languages and Benchmarks upon Applied Mathematics, Physics and Chemistry", available at <http://www.cs.berkeley.edu/~wkahan/SIAMjvnl.ps>:

           Published Benchmarks
        tend to be preoccupied with

                  SPEED

 to the near exclusion of everything else.

    Consequently, the Computer analog
            of Gresham’s Law
                 goes...

      "The Fast drives out the Slow,
           even if the Fast is

                  WRONG.”


(I tried to preserve the style of the original, which appears on page 14 of that diatribe.)

2) Many hardware architectures (including, I believe IA-64) defer floating point division to software anyway. So the bit-at-a-time remainder algorithm is probably reasonable. However, an alternative, if fused multiply-add is available, may be to take the absolute values of n and d, set the rounding mode to "towardzero" and then compute the inverse of the denominator. Then successively compute n = -fma(floor(n*inverse_d), d, -n) until n < d. (The fma will not lose precision in this computation.)

This is quite similar to the current definition of luai_nummmod, but with the rounding mode set correctly to start with (it has to be restored afterwards, of course), and with an iteration if necessary.

With respect to copysign:

Mike Pall is absolutely correct. Nonetheless, it is possible to define the Lua semantics of % in terms of the semantics of fmod().