• Subject: Re: 5.1 rc mod giving -0 (never just 0)
• From: Roberto Ierusalimschy <roberto@...>
• Date: Mon, 23 Jan 2006 11:36:29 -0200

```> > >  > for i = 50, 70 do io.write(math.fmod(2^i, 3), " ") end; io.write"\n"
> > > 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1
> > > [...]
> > At 2^54 we are beyond double capacity to show all digits.
> > So how does it know what the remainder is? Some form of
> > optimized arithmetic?
> [...]
> By using an iterative subtract-and-shift division algorithm.

That example seems only a big coincidence to me. When we call
math.fmod(2^i, 3), 2^i is computed and stored in memory, with only 54
mantissa bits. 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

> for i = 50, 70 do io.write(math.fmod(2^i + 1, 2), " ") end; io.write"\n"
1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

-- Roberto

```