  lua-l archive

• Subject: Re: Why do some math functions return -0
• From: David Kastrup <dak@...>
• Date: Mon, 20 Sep 2010 18:21:41 +0200

```bb <bblochl@arcor.de> writes:

> I use a lot of different scripting languages (JavaScript, Python, Ch -
> a C interpreter - and Lua) one more, the other less and compiled
> languages as well. Because of that lengthy discussion "Why do some
> math functions return -0" I actually checked the result of % of
> different languages:
>
> JavaScript-C 1.8.0 pre-release 1 2009-02-16 : -7%-9 = -7, 9%-7 = 2, 7%-9 = 7
>
> Ch Standard edition, version 6.3.0.14091:  -7%-9 = -7, 9%-7 = 2, 7%-9 = 7
>
> java version "1.6.0_0" OpenJDK  Runtime Environment (build
> 1.6.0_0-b11): -7%-9 = -7, 9%-7 = 2, 7%-9 = 7
>
> Python 2.5.2 (r252:60911, Jan 24 2010, 14:53:14) [GCC 4.3.2] on linux2
> : -7%-9 = -2, 9%-7 = -5, 7%-9 = -2
>
> Lua 5.1.3 : -7%-9 = -2, 9%-7 = -5, 7%-9 = -2
>
> Obviously Lua and python use the expression
> a - (n * math.floor(a/n))
> for the calculation of the %-operator.
>
> The other languages obviously use another formula with a different
> result, that equals to the other "C-like" languages.
>
> Concerning to some more studies in theat field I would no longer speak
> of a "bug" but different interpretations in different languages.

I have yet to see any rationale for returning -0 for positive operands.

> Lua and Python define the sign of the result from the divisor.
> JavaScript and Ch define the sign of the result from the dividend.
>
> There should be a strict math-definition of that modulo-operator,

Nonsense.  Mathematics does not use the % operator.  For "modulo", the
definition is quite clear: numbers differing by whole multiples of the
modulus are identical.  Quite a number of languages offer both a mod
operator as well as a rem operator.  K&R C does not define _either_, but
states that % should complement integer division.  If integer division
rounds towards -inf, you get the mod operator as result, if it rounds
towards 0, you get the rem operator.

That's rather insane, so ANSI C decided to define integer division with
rounding towards 0.  One rationale being that it is confusing if
-a%b is not the same as 0-a%b.

> GNU Octave, version 3.0.1: -7%-9 = -7, 9%-7 = 9, 7%-9 = 7
>
> Maxima 5.13.0 http://maxima.sourceforge.net Using Lisp GNU Common Lisp
> (GCL) GCL 2.6.7 (aka GCL): mod(-7,-9) = -7, mod(9,-7) = -5, mod(7,-9)
> = -2

gcl likely has both mod and rem as well.

> AXIOM Computer Algebra System Version: Axiom 3.9 (September 2005)
> Timestamp: Monday December 3, 2007 at 18:21:59 : rem(-7,-9) = -7,
> rem(9,-7) = 2, rem(7,-9) = 7
>
> Please tell me when you have found the truth of the %-operator!

Depends on its respective definition.  Math does not have a convention
for "%".

--
David Kastrup

```

• Follow-Ups: