Usually modulo operation is also called remainder operation, and both return the remainder as their result..remandmodThe only difference is:
When x and y have the same sign, the results of the two functions are identical; when x and y have different signs, the sign of the rem function result is the same as x, while mod follows y.
This is because the two functions have different generation mechanisms: rem uses the fix function, while mod uses the floor function (these two functions are used for rounding; fix rounds toward 0, and floor rounds toward negative infinity). The rem(x, y) command returns x - n.*y. If y is not equal to 0, where n = fix(x./y). And mod(x, y) returns x - n.*y; when y is not equal to 0, n = floor(x./y).
The value pattern for modulo of two integers with opposite signs (the same rule applies to decimals; this seems different from the C language)
First treat both integers as positive numbers, then perform division:
- 1. When divisible, the value is 0
- 2. When not divisible, value = divisor × (integer quotient + 1) - dividend
Example:mod(36,-10)=-4
That is: 36 divided by 10 gives integer quotient 3, plus 1 gives 4; its product with the divisor is 40; then the difference from the dividend is (40-36=4); take the sign of the divisor. So the value is -4.
Example: mod(9,1.2)=0.6;
Example:
>> mod(5,2) ans =1 % 除数是正,余数就是正 >> mod(-5,2) ans =1 >> mod(5,-2) ans =-1 % 除数是负,余数就是负 >> mod(-5,-2) ans =-1 % 用 rem 时,不管除数是正是负,余数的符号与被除数的符号相同 >> rem(5,2) ans =1 % 被除数是正,余数就是正 >> rem(5,-2); ans =1 >> rem(-5,2) ans =-1 % 被除数是负, 余数就是负 >> rem(-5,-2) ans =-1
Take your time to understand; they are indeed different.