lua-users home
lua-l archive

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


>Well, I find it weak defense to say that manual doesn't claim
>consistency (one may then consider this a manual issue). Because
>consistency in that case, is probably what we could normally expect from
>a language. Then it is surprising that Lua doesn't share code for % and
>math.mod and not very shocking to consider this a bug (or probably non
>wish able inconsistency for sensitive hears), especially when Lua
>enforces the rule one way and only one to do things especially to limit
>inconsistency risks and reduce code size.




You might find it interesting to know that there ARE two definitions of "mod." Specifically, computer scientists and mathematicians debate over this all the time.

Would you find it odd to realize that the two "different" implementations in Lua are actually the two disputed definitions?

> = -4 % 3
2
> =math.fmod(-4,3)
-1

Both of these are correct, depending on your definition.

-4 % 3 == 2: Formally written as "-4 (mod 3) == 2"

Repeatedly add 3 until you come to the largest number that is less than 3. You'll get 2.


math.fmod(-4, 3) == -1: Formally written as "-4 modulo 3 == 2"

Divide 4 by 3, you get 1 remainder 1. Negate this because it is negative, you get -1.



Technically there are an infinite number of solutions to "x (mod y) == z" and this is why you can see varying answers. However, it has been argued time and time again that "mod" is NOT the same as %. It is, however, not surprisingly unusual that varying implementations would exist. I wouldn't even be surprised if it was intentional. I personally advocate the fact that Lua has both of these DIFFERENT answers, both of which are correct, so that I can choose the desired value on my own. Granted, it would not be difficult to derive the other, but it is definitely convenient to have.


Some of you will think I'm on crack for saying that there are an infinite number of solutions, and I'm not surprised. Most people are trained into thinking that "5 (mod 2)" means "the remainder when 5 is divided into 2" even though this is incorrect. "9 = 5 (mod 2)" is a true statement. Those of you whom have taken a discrete structures course will agree with me (hopefully).

Should the argument that there are an infinite number of solutions be an excuse to go nuts with it? Well, no. In fact, "mod" is different from "modulus," and most programmers are expecting "modulus" even when using a function like math.fmod.

Should this be classified as a bug? I think absolutely not. There's nothing wrong here at all. Perhaps the manual could be a little clearer, but it never guaranteed that they would be the same, and more specifically, THEY ARE BOTH CORRECT.

</rant>

Regards,
-- Matthew P. Del Buono a.k.a. Shirik