应用中发现 np.mod(a,b)
与 torch.fmod(a,b)
的不同, 主要集中在有 负数
的情况下, 按照数学中的取余法则, 两个数取余, 余数总是为正数.
例如 (用 % 表示取余运算)
7%3=3x2+1,商为2, 余数为1
(-7)%(-3)=(-3)x3+2, 商为3, 余数为2
7%(-3)=(-3)x(-2)+1, 商为-2, 余数为1
(-7)%3=3x(-3)+2, 商为-3, 余数为2
(5)%(-0.5)=(-0.5)x(-1)+4.5, 商为-3, 余数为2
具体的规则可以看下 MATLAB 中的实现
>> help mod
mod Modulus after division.
mod(x,y) returns x - floor(x./y).*y
....
其中 floor()
是向下取整运算
>> floor(2.3)
ans =
2
>> floor(-0.5)
ans =
-1
对比 np.mod(a,b)
与 torch.fmod(a,b)
torch.fmod(torch.tensor(-0.5), 5)
tensor(-0.5000)
np.mod(-0.5, 5)
4.5
可以看到, np.mod()
更符合数学中的定义.