XML: Modulus Operator

From FSDeveloper Wiki
Jump to: navigation, search

XML: Modulus Operator

QUESTION: What does the expression "123 2 %" mean?

The modulus, or remainder, operator divides number1 by number2 and returns only the remainder as result.

The sign of result is the same as the sign of number1.

The value of result is between 0 and the absolute value of number2.


In XML syntax, the general statement is:

number1 number2 %


For example, in the following expression, A (which is result) equals 5.6.

A = 19 6.7 %

This is equivalent to:

19 / 6.7 = 2.8358208

We throw away the fraction leaving 2 as the result

Now we have:

A = 19 - (6.7 * 2)

Therefore A = 5.6


The above is an example where the result is certainly not obvious!

The "%" (or "mod") operator in computer languages is simply the remainder.

For example,

17 3 % = 2

because

17 / 3 = 5 rem 2

which in turn means

17 = 3 * 5 + 2


There are some tricky issues when negative numbers are used, but that shouldn't ordinarily be necessary.


In math (number theory), the term is used a little differently.

The "modulus" is actually not the remainder,

but the number you are dividing by;

and "mod" is not an operator,

but a label telling "in what sense two quantities are considered congruent, or equal."


For example, we would say

17 = 11 (mod 3)

(read as "17 is congruent to 11, modulo 3"), meaning that 17 and 11 both leave the SAME remainder when divided by 3. You probably won't see this usage if you are only reading about programming, but it's worth being aware of if you look deeper into the math behind it.

The expression a = b (% n) means that n is a divisor of a - b. This sentence is read, "a is congruent to b modulo n." It is something like a remainder, because if you subtract a remainder from the dividend, the divisor will go into the result evenly.

Examples: 100 = 86 (% 7), because 100 - 86 = 14 has 7 as a divisor. On the other hand, if you divide 100 by 7, the quotient is 14 and remainder is 2, and 100 = 2 (% 7), too.

Now, back to your original question, what would 123 2 % be?

A = 123 2 %

123 / 2 = 61.5, therefore:

A = 123 - (61 * 2)

A = 1

NOTA BENE: It was pointed out by "mgh" that the "XML modulus function" x y % in C/C++ is mathematically equivalent to:

(fabs(x)/x)*(fabs(x)-int(fabs(x)/fabs(y))*fabs(y))

Of course, since C/C++ has a defined function, actual usage would be:

fmod(x,y)

#include <math.h>
double fmod( double x, double y)