我最近发现代码中有一个bug,我可以用x / y替换np.divide(x, y)来修复它.

我的印象是np. divide(x,y)等同于x/y(numpy文档中也有这么多).

这是麻木中的一个错误,还是意料之中的行为?

正如我所说的,我眼前的问题已经解决了,所以我不太担心找到解决办法,我更好奇地想知道发生了什么.

import numpy as np


x1 = np.array([[281], [15831], [30280], [975], [313], [739], [252], [10364], [21480], [1447], [315], [772], [95], [2710], [7408], [215], [111], [158], [0], [88], [21], [661], [0], [0], [0], [5], [4], [0], [12], [0], [0], [50], [28], [0], [0], [272]])
x2 = np.array([[499], [6315], [33800], [580], [208], [464], [384], [3127], [19596], [2319], [218], [1740], [217], [411], [4250], [223], [406], [267], [2], [0], [16], [0], [0], [0], [0], [8], [3], [0], [18], [0], [1], [0], [41], [0], [0], [0]])
x3 = np.array([[507], [6180], [34005], [555], [200], [451], [390], [3024], [19492], [2425], [211], [1848], [223], [396], [4097], [224], [406], [282], [2], [0], [16], [0], [0], [0], [0], [8], [3], [0], [19], [0], [2], [0], [45], [0], [0], [0]])
x4 = np.array([[507], [6178], [34017], [554], [200], [451], [391], [3022], [19486], [2439], [210], [1865], [223], [396], [4089], [224], [406], [284], [2], [0], [16], [0], [0], [0], [0], [8], [3], [0], [19], [0], [2], [0], [46], [0], [0], [0]])

not_zero = (x1 + x2) != 0
x = np.divide(2*(x1 - x2)**2, x1 + x2, where=not_zero)
r = (2*(x1[not_zero] - x2[not_zero])**2) / (x1[not_zero] + x2[not_zero])
print("n1 =",x.max(),"\tt1 =", r.max())

not_zero = (x2 + x3) != 0
x = np.divide(2*(x2 - x3)**2, x2 + x3, where=not_zero)
r = (2*(x2[not_zero] - x3[not_zero])**2) / (x2[not_zero] + x3[not_zero])
print("n2 =",x.max(),"\tt2 =", r.max())

not_zero = (x3 + x4) != 0
x = np.divide(2*(x3 - x4)**2, x3 + x4, where=not_zero)
r = (2*(x3[not_zero] - x4[not_zero])**2) / (x3[not_zero] + x4[not_zero])
print("n3 =",x.max(),"\tt3 =", r.max())

Output:

n1 = 8177.933351395286  t1 = 8177.933351395286
n2 = 873842.0           t2 = 6.501672240802676
n3 = 1322.0             t3 = 0.15566927013196877

Python版本:3.7.6 Numpy版本:1.17.0

推荐答案

没有参数out的参数where = mask有点危险.在没有输出目标的情况下,该函数构建一个适当形状的np.empty数组,然后用输出数据替换空数组的某个子集.

np.empty不是空的 它只是一个没有初始化的随机内存位置(所以它仍然有以前存在于该内存块中的任何垃圾数据). 所以在mask = False处,你的输出将是剩余的随机垃圾. 如果这个内存块碰巧有二进制垃圾,可以编码成一个比你的其他数据更大的数字,它最终是你的max值.

你可以再次用not_zero作为掩膜来遮盖垃圾:

x = np.divide(2*(x1 - x2)**2, x1 + x2, where=not_zero)[not_zero]

或者自己初始化输出数组:

x = np.zeros_like(x1)
np.divide(2*(x1 - x2)**2, x1 + x2, where = not_zero, out = x)

Python相关问答推荐

仅从风格中获取 colored颜色 循环

在Python中对分层父/子列表进行排序

韦尔福德方差与Numpy方差不同

scikit-learn导入无法导入名称METRIC_MAPPING64'

如何列举Pandigital Prime Set

C#使用程序从Python中执行Exec文件

为什么默认情况下所有Python类都是可调用的?

如何调整QscrollArea以正确显示内部正在变化的Qgridlayout?

如何让这个星型模式在Python中只使用一个for循环?

我如何根据前一个连续数字改变一串数字?

cv2.matchTemplate函数匹配失败

Pandas Data Wrangling/Dataframe Assignment

如何检测鼠标/键盘的空闲时间,而不是其他输入设备?

循环浏览每个客户记录,以获取他们来自的第一个/最后一个渠道

巨 Python :逆向猜谜游戏

一个telegram 机器人应该发送一个测验如何做?""

如何将相同组的值添加到嵌套的Pandas Maprame的倒数第二个索引级别

简单 torch 模型测试:ModuleNotFoundError:没有名为';Ultralytics.yolo';

如何提高Pandas DataFrame中随机列 Select 和分配的效率?

如何通过特定导入在类中执行Python代码