技术背景
求余数,是一个比较简单的数学计算,内容就不展开介绍了。在不同的工具中,在实现余数计算这个操作的时候,有可能有不同的结果。这里介绍的是Python、Numpy和PyTorch中的几种不同的计算余数的方法。
计算示例
首先最简单的,演示一下Python原生的余数计算方法:
In [1]: -0.5%5
Out[1]: 4.5
这个意思就是说,-0.5对5求余数,得到的结果是4.5,那么也是数学上所预期的正确结果。然后看一下numpy的余数计算:
In [1]: import numpy as np
In [2]: a = np.array([-0.5])
In [3]: b = np.array([5])
In [4]: a%b
Out[4]: array([4.5])
In [5]: np.mod(a,b)
Out[5]: array([4.5])
numpy的计算结果跟数学上的预期是一致的,不论是哪个函数。接下来再看一下pytorch的几个求余数接口:
In [1]: from torch import tensor, fmod, remainder
In [2]: a = tensor([-0.5])
In [3]: b = tensor([5])
In [4]: a%b
Out[4]: tensor([4.5000])
In [5]: fmod(a,b)
Out[5]: tensor([-0.5000])
In [6]: remainder(a,b)
Out[6]: tensor([4.5000])
其中比较特殊的一个是fmod
函数。从数学上来说,余数我们一般只取正数,但是fmod的计算结果可以有负数:
In [1]: from torch import tensor, fmod
In [2]: a = tensor([-5.5])
In [3]: b = tensor([5])
In [4]: fmod(a,b)
Out[4]: tensor([-0.5000])
In [5]: a = tensor([-4.9])
In [6]: fmod(a,b)
Out[6]: tensor([-4.9000])
因此,pytorch中的remainder
函数才是我们正常所理解的求余数操作,也直接使用a%b
这样的写法。
总结概要
本文通过几个示例,介绍了在Python、Numpy和PyTorch三个不同的框架下,对于求余数函数的定义。比较特殊的是pytorch中的fmod函数,并不符合数学上的求余数方法,而是需要使用remainder函数。
版权声明
本文首发链接为:https://www.cnblogs.com/dechinphy/p/torch_mod.html
作者ID:DechinPhy
更多原著文章:https://www.cnblogs.com/dechinphy/
请博主喝咖啡:https://www.cnblogs.com/dechinphy/gallery/image/379634.html