【问题标题】:Is there a way to have NumPy arrays calculate 0 * inf = 0 rather than 0 * inf = NaN?有没有办法让 NumPy 数组计算 0 * inf = 0 而不是 0 * inf = NaN?
【发布时间】:2021-05-11 15:16:40
【问题描述】:

我使用 NumPy 数组来表示函数和概率分布。我希望数组遵守0 * inf 产生0 的约定(概率上很常见)。

我愿意

  • array([1., inf]) @ array([1., 0.]) 产生 1.0
  • array([1., inf]) @ array([1., 1.]) 产生 inf

我该怎么做? NumPy 中是否有我可以更改的设置?我应该继承类ndarray吗?

编辑---一个想法:

class parray(np.ndarray):
    def __matmul__(self, other):
        return np.matmul(np.nan_to_num(self), np.nan_to_num(other))

EDIT 2---结合orlp的建议:

class parray(np.ndarray):
    def __matmul__(self, other):
        a = np.matmul(np.nan_to_num(self), np.nan_to_num(other))
        a[a > 1e90] = inf
        return a

【问题讨论】:

  • 你是对的。我会编辑帖子!
  • 哦,很好。让我超级困惑。

标签: python arrays numpy nan


【解决方案1】:

我认为你最好的选择是选择一些大数字(例如1e100)并用它来表示无穷大。

然后您可以进行计算(注意RuntimeWarning: overflow encountered 以确保您的大数不会回到inf),如果需要,将上面的任何内容转换为1e90 回到无穷大。

【讨论】:

    猜你喜欢
    • 2016-01-03
    • 2017-04-13
    • 2021-03-13
    • 2020-06-14
    • 2012-10-05
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多