[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Modulo infinity
- From: Dirk Laurie <dirk.laurie@...>
- Date: Tue, 1 Apr 2014 10:41:17 +0200
2014-03-31 23:46 GMT+02:00 Dan Tull <dtull@adobe.com>:
> Out of curiosity (apologies if I'm missing something obvious), why isn't % the same as fmod?
>
> in luaconf.h:
> #define luai_nummod(a,b) ((a) - floor((a)/(b))*(b))
There are three reasons.
Main reason: % always gives a non-negative result, even for negative x,
whereas fmod(x,y) gives a result of the same sign as x.
$ lua
Lua 5.2.3 Copyright (C) 1994-2013 Lua.org, PUC-Rio
> =-5%3
1
> =math.fmod(-5,3)
-2
C reason:
fmod is part of the IEEE 754 specification. Your CPU has a machine
instruction that
can calculate fmod(x,y) given two doubles. According to the standard,
it must give
the closest possible machine number to the correct result. It would be
madness for
an implementor of the C math library, coding in assembly language, not
to exploit that
instruction.
But that instruction is not available from C via the % operator,
because that operator
is defined for integers only.
So in C the two things are totally different.
Accuracy reason:
> In some cursory checking, they return results that are almost always equal
> (or different only at the 12th decimal place or so)
Lua up to 5.2 had no integers, so % had to be defined for Lua numbers, and the
definition you quote is it. Frankly, it is a hack. Since it translates
to three actual
operations, it cannot achieve the same accuracy that a single instruction would
unless both operands are integers.
> aside from this discrepancy around infinity as the second operand.
You can see from the definition of the macro why you get NaN.
> I suppose regardless of the reason, anybody that cares about this case
> can tweak luaconf.h to swap in fmod for luai_nummod's definition easily
> enough.
The longer I use Lua, the more I realize that patches to the source should
be restricted to C applications with embedded Lua, whose source is distributed
complete with the exact version of Lua that it uses. You get a warm feeling
of content when doing your daily work with your favourite patch enabled,
but the moment you want to share/publish your code, the incompatibilities
become obnoxious.