取模和求余数的区别
先导知识
- fix,向0取整,fix(-3.14) = -3
- floor,向负无穷取整 ,floor(-3.14) = -4
取模 mod
取模是在模运算的基础上求得的余数
b = mod(a,m),这是matlab的帮助文档
b = mod(a,m)
returns the remainder after division ofa
bym
, wherea
is the dividend andm
is the divisor. This function is often called the modulo operation, which can be expressed as b = a - m.*floor(a./m).
mod(a,0) = a
mod(-5,3) = -5 - 3*floor(-5/3) = -5 - 3* (-2) = 1
求余数 rem
求余数是在除法的基础上取得的余数
r = rem(a,b)
r = rem(a,b)
returns the remainder after division ofa
byb
, wherea
is the dividend andb
is the divisor. This function is often called the remainder operation, which can be expressed as r = a - b.*fix(a./b).
rem(a,0) = 无穷小量
rem(-5,3) = -5 - 3*fix(-5,3) = -5 - 3*(-1) = -2
此外1,经过测试,在C/C++, C#, JAVA,PHP这几门主流语言中,’%’运算符都是做取余运算,而在python中的’%’是做取模运算[1]。
此外2,余数在数学中的定义是始终大于等于0的,而对于某些编程语言的取余运算不是按照上面的定义来执行的,因此才会出现余数小于0的情况[1]。
因此,在代码移植和数值计算的时候要特别小心,这种bug一般是找不出来的。
参考:[1] : https://blog.csdn.net/u012142247/article/details/79445820