为什么numpy.prod()对于一长串自然数会错误地返回负数或0? [英] Why is numpy.prod() incorrectly returning negative results, or 0, for my long lists of natural numbers?

查看:255
本文介绍了为什么numpy.prod()对于一长串自然数会错误地返回负数或0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Euler项目问题12 ,所以我需要对数字进行一些测试是500多个独特因素的倍数.

I'm just working on Project Euler problem 12, so I need to do some testing against numbers that are multiples of over 500 unique factors.

我认为数组[1、2、3 ... 500]是一个很好的起点,因为该数组的乘积是此类数字中可能的最小值.但是,numpy.prod()返回此数组的 zero .我确定我缺少明显的东西,但是到底是什么呢?

I figured that the array [1, 2, 3... 500] would be a good starting point, since the product of that array is the lowest possible such number. However, numpy.prod() returns zero for this array. I'm sure I'm missing something obvious, but what the hell is it?

>>> import numpy as np
>>> array = []
>>> for i in range(1,100):
...   array.append(i)
... 
>>> np.prod(array)
0
>>> array.append(501)
>>> np.prod(array)
0
>>> array.append(5320934)
>>> np.prod(array)
0

推荐答案

请注意, Python使用无限"整数,但是在numpy中,所有类型都被键入,因此这里是"C"风格(可能是64位)整数.您可能正在发生溢出.

Note that Python uses "unlimited" integers, but in numpy everything is typed, and so it is a "C"-style (probably 64-bit) integer here. You're probably experiencing an overflow.

如果您查看 numpy.prod ,您可以看到dtype参数:

返回数组的类型,以及与元素相乘的累加器的类型.

The type of the returned array, as well as of the accumulator in which the elements are multiplied.

您可以做一些事情:

  1. 拖放回Python,并使用其无限整数"相乘(请参阅该问题(有关如何操作).

请考虑您是否真的需要找到如此庞大数量的乘积.通常,当您使用非常小或非常大的乘积时,会切换到对数和.正如@WarrenWeckesser指出的那样,这显然是不精确的(这不像最后采用指数会为您提供确切的解决方案),而是用来衡量一种产品的增长速度是否比另一种产品快.

Consider whether you actually need to find the product of such huge numbers. Often, when you're working with the product of very small or very large numbers, you switch to sums of logarithms. As @WarrenWeckesser notes, this is obviously imprecise (it's not like taking the exponent at the end will give you the exact solution) - rather, it's used to gauge whether one product is growing faster than another.

这篇关于为什么numpy.prod()对于一长串自然数会错误地返回负数或0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆