top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

get negative from prod(x) when x is positive integers using python

0 votes
449 views

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?

posted Jun 28, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

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)
-**********
>>> 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
answer Jun 28, 2013 by anonymous
Similar Questions
+1 vote

For example gcd(3, -7) returns -1, which means that a co-prime test that would work in many other languages 'if gcd(x, y) == 1' will fail in Python for negative y.

And, of course, since -|x| is less than |x|, returning -|x| rather than |x| is not returning the greatest common divisor of x and y when y is negative.

+1 vote

For example:

a=[-15,-30,-10,1,3,5]

I want to find a negative and a positive minimum.

example: negative
print(min(a)) = -30

positive
print(min(a)) = 1
+3 votes

import datetime
datetime.datetime.fromtimestamp(**********)
datetime.datetime(2004, 8, 17, 17, 0)

Is there a way to know if the timestamp has a microseconds?

...