Fwd: KCalc - Modulo Function

Gunnar Schmi Dt gunnar at schmi-dt.de
Mon Feb 13 14:22:28 GMT 2006


Hello,

On Monday 13 February 2006 13:43, Josef Spillner wrote:
> El Lunes, 13. Febrero 2006 14:19, Mirko Boehm escribió:
> > Entering -7 mod 3 in the KCALC number field results in 2.
>
> FWIW, python also returns 2, and has a FAQ entry about this:
> http://www.python.org/doc/faq/programming.html#why-does-22-10-return-3
>
> This hit me recently too, although I don't have an opinion on its
> correctness.

Both "-7 mod 3 = -1" and "-7 mod 3 = 2" are correct. If I read the mail 
from the original author correctly he requests that "-7 mod 3 = 1", which 
is mathematically wrong.

Mathematically we can define the "mod"-operator as the remainder of an 
integer division:

   "a mod b = a - b * (a div b)"

Depending on the value returned by the integer division "a div b" the 
remainder "-7 mod 3" might either be "-1" or "2":

a) -7 mod 3 = -7 - 3 * (-7 div 3) = -7 - 3*(-2) = -1
b) -7 mod 3 = -7 - 3 * (-7 div 3) = -7 - 3*(-3) = 2

The corresponding values for "a div b" can mathematically be defined as:

a1) a div b = sign(a*b) * | abs (a/b) |
a2) a div b = [ a/b ]
b) a div b = | a/b |

where "| a/b |" is the floor-operation (the next smaller integer number so 
that "a/b - 1 < | a/b | <= a/b") and "[ a/b ]" responds to simply rounding 
to the nearest integer number ("a/b - 0.5 < [ a/b ] <= a/b + 0.5").

In computer programs it is easier if we use either definition a2 or b for 
the value of "a div b". Windows uses definition a1.

Gunnar Schmi Dt



-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
URL: <http://mail.kde.org/pipermail/kde-core-devel/attachments/20060213/c9afb178/attachment.sig>


More information about the kde-core-devel mailing list