首页 > 解决方案 > np.multiply.reduce 不会抛出 FloatingPointError 但单元素乘法会抛出

问题描述

给定以下代码段,为什么不np.multiply.reduce提高FloatingPointErrorarr[0] * arr[1]确实提高了?这是一个错误吗?

import numpy as np
import sys

print(np.__version__, sys.version)
# 1.20.3 3.9.5 (tags/v3.9.5:0a7dcbd, May  3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)]


arr = np.array([-54588, 1235845941])

# (1)
with np.errstate(all='raise'):
  result = np.multiply.reduce(arr)
# result is -1306909036 but there should have been a FloatingPointError, shouldn't it?


# (2)
with np.errstate(all='raise'):
  result = arr[0] * arr[1]
# ---------------------------------------------------------------------------
# FloatingPointError                        Traceback (most recent call last)
# <ipython-input-17-7a30d8c0933e> in <module>
#       1 with np.errstate(all='raise'):
# ----> 2   result = arr[0] * arr[1]
#       3

# FloatingPointError: overflow encountered in long_scalars

这与numpy-doesnt-throw-floatingpointerror-for-dot-product 有关吗?

标签: python-3.xnumpynumpy-ufunc

解决方案


推荐阅读