Daily programming often comes into contact with the remainder/modulus operation, so how is the remainder/modulo operation defined in the computer?
P1: Four "rounding" methods
mathematical rounding
1.1 Round to 0
parseInt() 注意接受参数是string;所以调用该方法时存在类型转换
parseInt(3.141592654) // 3
1.2 Round down
Math.floor() 不四舍五入
Math.floor(1.5555) // 1
1.3 Round up
Math.ceil() 向上取整
Math.ceil(1.5555) // 2
Math.ceil(1.1555) // 2
1.4 Rounding off
Math.round() 四舍五入取整
Math.round(1.5555) //2
Math.round(1.4999) //1
P2: Use formulas to understand "modulo"
Modulo concept
If a and d are two natural numbers and d is non-zero, it can be proved that there are two unique integers q and r, satisfying
a = q*d + r 且 0 ≤ r < d
. where q is called the quotient and r is called the remainder.
Operator --- remainder operation %
P3: Is "remainder" the same as "modulo"?
Rounding
Remainder: Make the quotient as far as possible, and round to 0.
Modulo: Make the quotient as far as possible, and round towards -∞.
In C, % is essentially taking the remainder.
% in Python is actually a modulo.
Understand the chain:
For any number greater than 0, perform 0-direction rounding and -∞ rounding, and the rounding direction is the same. So taking the modulus is equivalent to taking the remainder
For any number less than 0, perform 0-direction rounding and -∞ rounding, and the rounding direction is opposite. Therefore, taking the modulus is not equivalent to taking the remainder
The quotient obtained by dividing with the symbol data must be a positive number (positive number vs positive integer), that is, greater than 0! Therefore, when rounding the quotient, taking the modulus is equivalent to taking the remainder.
P4: Summary
- There are many rounding methods for floating point numbers (or division of integers), such as rounding to 0, rounding to (positive, negative) infinity, rounding and rounding...
- If a and d are two natural numbers, and d is non-zero, it can be proved that there are two unique integers q and r, satisfying a = q*d + r, q is an integer, and 0 ≤ |r|< |d|. where q is called the quotient and r is called the remainder
- In different languages, the results of "modulo" are different for the same calculation expression. We can call them the positive and negative remainders respectively
- The size of the specific remainder r essentially depends on the quotient q. And the quotient depends on the rounding rules when calculating the division.
- Remainder vs Modulo: Remainder is to get the quotient as far as possible and round towards 0. The modulus is to get the quotient as far as possible, rounding towards -∞.
- If the two data involved in the remainder have the same sign, taking the modulus is equivalent to taking the remainder
- If the two data symbols involved in the remainder are different, in C language (or other languages that use rounding towards 0 such as: C++, Java), the symbol of the remainder is the same as the dividend. (Because it is rounded towards 0)