consistent modulo-operator %

Got an idea for enhancing PureBasic? New command(s) you'd like to see?
Froggerprogger
Enthusiast
Enthusiast
Posts: 423
Joined: Fri Apr 25, 2003 5:22 pm
Contact:

consistent modulo-operator %

Post by Froggerprogger »

Hi!

PB's modulo is inconsistent with other languages and inconsistent to itself, see here why:

The 'problem':
When using mod to a power of 2, e.g. "a % 16" the compiler 'optimizes' to use a & 16 instead of modulo. Other languages (at least Java and C) doesn't. But this optimization changes the given result (and breaks a consequent symmetric approach - see below)!

So Java and C give:

Code: Select all

int a = -7;
b = a % 4; // gives -3
c = a % 5; // gives -2
which is corresponding to the 'symmetric' definition of modulo. At German Wikipedia there was an article about: There are two definitions of modulo:
1) mathematically: a % n lies between 0 and n-1
2) symmetrically: a % n lies between -(n-1) and n-1 and keeps the sign for symmetry (-a) % n = - (a % n). This way is implemented in nearly all programming languages. PB does it this way - but not for n be a constant power of 2:

PB gives

Code: Select all

a.l = -7;
b = a % 4; // 1
c = a % 5; // -2
which is mathematically correct too, but inconsistent with other programming languages, which are consequently symmetric.
There you could ran into troubles when translating from other languages into PB. Imagine there's somewhere in a C-program used Abs(x % 128) to map any value into -127...127. Translating to PB by Abs(x % 128) will give totally other results, e.g. C would give Abs(-3 % 128) = 3, while PB would give Abs(-3 % 128) = 125. This could lead into hard to find bugs.

Further PB is inconsequent:
It is

Code: Select all

a.l = -7;
Debug a % 4; // gives 1

Debug -7 % 4; // gives -3

; and even worse:
b.q = -7
Debug b % 4; // gives -3, too
So increasing the type from long to quad will result in possibly different behaviour, e.g. when using e.g. Abs(a % 128) even inside PB!

So the request is:
Please remove the optimization for powers of 2 to keep a consequent symmetric approach to be common with other languages and to be consistent inside PB.
%1>>1+1*1/1-1!1|1&1<<$1=1