我对numpy.heaviside函数有一些问题。本质上,当我似乎将相同的值传递给函数时,它给出了不同的结果。
根据它给出的文件
0 if x1 < 0
heaviside(x1, x2) = x2 if x1 == 0
1 if x1 > 0我认为问题在于x1==0的比较。原则上有两种选择:
我原以为numpy可以做1,但现在我认为它可以做2。
有什么办法可以绕过这个问题吗?
发布于 2019-05-04 17:34:48
我自己解决的。问题似乎确实在于numpy.heaviside使用了np.equal-like零检查。下面是一个使用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. ]https://stackoverflow.com/questions/55984798
复制相似问题