输入 input 元素用于被除数的数组other 元素用于除数的数组或者数rounding_mode 输入为字符串类型 用于判断结果的舍入类型 有以下三种情况 None 默认行为 不执行舍入操作。trunc 将除法结果向零四舍五入 相当于C语言风格的除法。floor 将除法结果四舍五入
注意
该运算支持广播机制 并且还支持整数、浮点数和复杂输入 始终将整数类型提升为默认标量类型torch.div可以通过a.div实现 后者默认a当做被除数 代码案例一般用法
import torch a torch.arange(20).reshape(5,4) b torch.arange(21,41).reshape(5,4) c torch.div(a,b) print(a) print(b) print(c)
输出
# 被除数 tensor([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19]]) tensor([[21, 22, 23, 24], [25, 26, 27, 28], [29, 30, 31, 32], [33, 34, 35, 36], [37, 38, 39, 40]]) # div结果(不进行舍入操作) tensor([[0.0000, 0.0455, 0.0870, 0.1250], [0.1600, 0.1923, 0.2222, 0.2500], [0.2759, 0.3000, 0.3226, 0.3438], [0.3636, 0.3824, 0.4000, 0.4167], [0.4324, 0.4474, 0.4615, 0.4750]])
rounding_mode三种方式的区别
import torch import numpy as np a torch.from_numpy(np.random.randn(2,5)) b torch.from_numpy(np.random.randn(2,5)) c torch.div(a,b) d torch.div(a,b,rounding_mode trunc ) e torch.div(a,b,rounding_mode floor ) print(a) print(b) print(c) print(d) print(e)
输出
# 被除数 tensor([[-0.1634, 1.6856, -0.0897, -0.7464, 1.3927], [-0.9697, 0.2859, 0.2458, 0.3014, 0.0339]], dtype torch.float64) tensor([[ 0.2383, 0.8596, -0.0589, -1.5333, 0.6570], [-0.3662, 0.1371, -0.1085, -0.0345, 0.2491]], dtype torch.float64) # 默认情况下 不进行舍入操作 tensor([[-0.6858, 1.9609, 1.5221, 0.4868, 2.1197], [ 2.6481, 2.0850, -2.2658, -8.7355, 0.1361]], dtype torch.float64) # trunc方式的舍入 tensor([[-0., 1., 1., 0., 2.], [ 2., 2., -2., -8., 0.]], dtype torch.float64) # floor方式的舍入 tensor([[-1., 1., 1., 0., 2.], [ 2., 2., -3., -9., 0.]], dtype torch.float64)
trunc与floor最主要的差别就是负数的四舍五入方法 trunc向零四舍舍入 floor普通的四舍五入 trunc得到的负数结果始终比floor得到的负数结果大1。
官方文档torch.div() https://pytorch.org/docs/stable/generated/torch.div.html?highlight div#torch.div



