问题出现在numpy.prod函数上(将正数相乘得到负数)。

huangapple go评论63阅读模式
英文:

Problem with numpy.prod (gives negative numbers multiplying positive numbers)

问题

为什么会发生这种情况 -

np.prod(np.arange(1,34))>0
是真的,但
np.prod(np.arange(1,32))>0
是假的
???

我尝试将前100个数字相乘
np.prod(np.arange(1,100))

这给了我0,所以我尝试找出问题,但我找不到。

英文:

Can someone explain to me, why this happens -

np.prod(np.arange(1,34))>0

is true but
np.prod(np.arange(1,32))>0
is false
???

I tried multiplying the first 100 numbers with
np.prod(np.arange(1,100))

This gave me 0, so I tried finding the problem, but I couldn't.

答案1

得分: 1

I just dealt with this, the problem is overflow.
我刚刚处理过这个问题,问题是溢出。

A Python int won't overflow, but numpy uses types like int32 and int64 which have limits on values that they can hold.
Python 的 int 不会溢出,但 numpy 使用 int32 和 int64 这样的类型,它们对可以保存的值有限制。

If you approach the limit that the numpy variable can hold you risk an invalid result that may look ok, an apparent invalid result, or a zero.
如果接近 numpy 变量可以容纳的限制,您可能会面临一个看起来正常的无效结果,一个明显的无效结果,或者是零。

If you need values like this, you can't use numpy. Just use the regular Python int.
如果您需要这样的值,就不能使用 numpy。只需使用普通的 Python int。

Here's the doc link which discusses this more: https://numpy.org/doc/stable/user/basics.types.html#overflow-errors
以下是讨论这个问题更多信息的文档链接:https://numpy.org/doc/stable/user/basics.types.html#overflow-errors

英文:

I just dealt with this, the problem is overflow.

A Python int won't overflow, but numpy uses types like int32 and int64 which have limits on values that they can hold.

If you approach the limit that the numpy variable can hold you risk an invalid result that may look ok, an apparent invalid result, or a zero.

If you need values like this, you can't use numpy. Just use the regular Python int.

Here's the doc link which discusses this more: https://numpy.org/doc/stable/user/basics.types.html#overflow-errors

答案2

得分: 0

按照Chase LP的解释,您可以通过使用astype()方法进行强制类型转换或直接使用math.factorial来解决问题。

np.prod(np.arange(1,100).astype(float))>0
np.math.factorial(100)>0

英文:

as explained by Chase LP , you can solve the issue by force typecasting using astype() method or just straight up use math.factorial if that is what you want

np.prod(np.arange(1,100).astype(float))>0
np.math.factorial(100)>0

huangapple
  • 本文由 发表于 2023年5月14日 15:14:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76246294.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定