python - numpy.heaviside 和机器精度

标签 python numpy

我对numpy.heaviside有一些问题功能。本质上,当我似乎将相同的值传递给函数时,它会给出不同的结果。

根据它给出的文档

                      0   if x1 < 0
heaviside(x1, x2) =  x2   if x1 == 0
                      1   if x1 > 0

我相信问题在于x1==0比较。原则上有两种选择:

  1. 检查该值是否为零且符合机器精度。
  2. 检查该值是否实际上为零。

我认为 numpy 会做 1.,但现在我认为它会做 2.

有什么办法可以避免这个问题吗?

最佳答案

我自己解决了。问题似乎确实是 numpy.heaviside 使用 np.equal - 就像零检查一样。这是一个使用 np.isclose 的函数相反。

import numpy as np
def heaviside_close(x1, x2):
    closeCheck = np.isclose(x1, np.zeros_like(x1))
    heavisideBare = np.heaviside(x1, 0.0)
    zeroVal = np.where(closeCheck, x2, 0.0)-np.where(closeCheck, heavisideBare, np.zeros_like(heavisideBare))
    result = heavisideBare+zeroVal
    return result
print(heaviside_close(np.asarray([-1., -0.1, 1e-20, 0.1, 1.]), 0.5))
# >>> [0.  0.  0.5 1.  1. ]
print(np.heaviside(np.asarray([-1., -0.1, 1e-20, 0.1, 1.]), 0.5))
# >>> [0.  0.  1.  1.  1. ]

关于python - numpy.heaviside 和机器精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55984798/

相关文章:

python - '_sre.SRE_Pattern' 对象在 Python 3.4 中不可迭代

python - 使用 numpy 扩展的 C 程序的 Makefile

python - 在 databricks 集群中使用 init 脚本安装 python 包

python - 在 python、opencv2、numpy 中获取图像蒙版上特征位置的索引

python - django:管理员通知,如果是 super 用户则显示

python - 如何使用 pandas 数据框打开 csv 文件

python - 使用 Pandas 滚动相关时如何处理不一致的结果?

numpy - 神经网络不良结果

python - 如何在Python中将一维径向轮廓转换为二维数组

python - 用 0 填充空白列