取模和求余数的区别

取模和求余数的区别

先导知识
  1. fix,向0取整,fix(-3.14) = -3
  2. floor,向负无穷取整 ,floor(-3.14) = -4
取模 mod

取模是在模运算的基础上求得的余数

b = mod(a,m),这是matlab的帮助文档

b = mod(a,m) returns the remainder after division of a by m, where a is the dividend and m 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 of a by b, where a is the dividend and b 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值