python - Nunmpy sum() function + comprehensions: int32 or in64? -
why numpy.sum , numpy.prod function return int32 when input list of int, , int64 if it's generator same list? what's best way coerce them use int64 when operating on list?
e.g.
sum([x x in range(800000)]) == -2122947200 sum((x x in range(800000))) == 319999600000l
python 2.7
you using numpy.sum
instead of built-in sum
, side effect of from numy import *
. advised not so, cause no end of confusion. instead, use import numpy np
, , refer numpy namespace short np
prefix.
to answer question, numpy.sum
makes accumulator type same type of array. on 32-bit system, numpy coerces list int32 array, causes numpy.sum
use 32-bit accumulator. when given generator expression, numpy.sum
falls calling sum
, promotes integers longs. force use of 64-bit accumulator array/list input, use dtype
parameter:
>>> np.sum([x x in range(800000)], dtype=np.int64) 319999600000
Comments
Post a Comment