lua-users home
lua-l archive

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


Hi,

Roberto Ierusalimschy wrote:
> That example seems only a big coincidence to me.

I beg to differ.

> When we call
> math.fmod(2^i, 3), 2^i is computed and stored in memory, with only 54
> mantissa bits.

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

This was the whole intention of the example: generating exact
numbers with huge exponent differences and taking their modulus
(and not getting an exact result). Dito for 2^i + 2^(i-1) etc.

> When Lua reads it back, there is no information available
> about the other bits. Lua cannot recreate them! Actually, several
> other similar cases fail with fmod. For instance:
> 
> > for i = 50, 70 do io.write(math.fmod(2^i + 1, 3), " ") end; io.write"\n"
> 2 0 2 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1

This has nothing to do with math.fmod. _Generating_ the number
2^i+1 needs i+1 bits of precision. It is rounded to 2^i if i is
too large _before_ even touching fmod. The fmod results are
correct and exact.

The '%' results are not:

  for i = 50, 70 do io.write((2^i + 1) % 3, " ") end; io.write"\n"
  2 0 2 2 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 

But as I argued in my previous post, this is probably not a good
reason to change the behaviour of '%'.

Bye,
     Mike