? get negative from prod(x) when x is positive integers

Peter Otten __peter__ at web.de
Fri Jun 28 11:01:30 EDT 2013


Vincent Davis wrote:

> I have a list of a list of integers. The lists are long so i cant really
> show an actual example of on of the lists, but I know that they contain
> only the integers 1,2,3,4. so for example.
> s2 = [[1,2,2,3,2,1,4,4],[2,4,3,2,3,1]]
> 
> I am calculating the product, sum, max, min.... of each list in s2 but I
> get negative or 0 for the product for a lot of the lists. (I am doing this
> in ipython)
> 
> for x in s2:
>     print('len = ', len(x), 'sum = ', sum(x), 'prod = ', prod(x), 'max =
>     ',
> max(x), 'min = ', min(x))
> 
> ...
> 
> ('len = ', 100, 'sum = ', 247, 'prod = ', 0, 'max = ', 4, 'min = ', 1)
> ('len = ', 100, 'sum = ', 230, 'prod = ', -4611686018427387904, 'max =
> ', 4, 'min = ', 1)
> ('len = ', 100, 'sum = ', 261, 'prod = ', 0, 'max = ', 4, 'min = ', 1)
> 
> .....
> 
> ('prod =', 0, 'max =', 4, 'min =', 1)
> ('prod =', 1729382256910270464, 'max =', 4, 'min =', 1)
> ('prod =', 0, 'max =', 4, 'min =', 1)
> 
> ....
> 
> 
> Whats going on?

Instead of Python's integer type (int/long) numpy uses the faster machine 
integers (typically 32 or 64 bit) that overflow:

>>> a = numpy.array([0xffffffff, 0xffffffff])
>>> numpy.prod(a)
-8589934591
>>> a.dtype
dtype('int64')

As a workaround you can use Python's ints (slower)

>>> a = numpy.array([0xffffffff, 0xffffffff], dtype=object)
>>> numpy.prod(a)
18446744065119617025L

or float (loss of precision)

>>> a = numpy.array([0xffffffff, 0xffffffff], dtype=float)
>>> numpy.prod(a)
1.8446744065119617e+19





More information about the Python-list mailing list