[SciPy-user] summation of array elements

David M. Cooke cookedm at physics.mcmaster.ca
Wed Jun 30 15:37:49 CDT 2004


On June 30, 2004 03:06 pm, Travis E. Oliphant wrote:
> Horst Horstsen wrote:
> > Hi Scipy-Experts,
> >
> > I've got a question concerning the summation of elements in an array.
> > The following small sample programm illustrates the problem:
> >
> > _________________________________
> > from scipy.xplt import *
> > from RandomArray import *
> >
> > nx,ny=100,10
> >
> > def gen_lattice(nx,ny,c):
> >     x=uniform(0.0,1.0,((nx,ny)))
> >     return (x<c)
> >
> > c=1
> > x=gen_lattice(nx,ny,c)
> > print sum(x)
> > print sum(ravel(x))
> > ___________________________________
>
> The problem is that you are using Numeric's sum instead of scipy's sum
> and the x<c returns an array of 8 bit integers which is overflowing
> (Numeric's sum is just short for add.reduce).
>
> SciPy's sum check's this case.

It's not a problem with Numeric; replacing 'from scipy.xplt import *' with 
'from Numeric import *' gives the expected result (1000). The original code 
gives me the same result as the OP, 232. Using 'from scipy import *' instead 
also gives me 1000. So there's something funny about importing scipy.xplt.

So, this works:

import Numeric
import RandomArray

nx, ny = 300, 10
def gen_lattice(nx, ny, c):
    x = RandomArray.uniform(0.0, 1.0, ((nx, ny)))
    return (x < c)

c = 1
x = gen_lattice(nx, ny, c)
print x.typecode()
print Numeric.sum(x)
print Numeric.sum(Numeric.ravel(x))

Output:
l
[300 300 300 300 300 300 300 300 300 300]
3000


BUT! putting an 'import scipy' into there makes it not work:

import Numeric
import RandomArray
import scipy
#... same code (with no calls to any scipy code)

Output:
b
[44 44 44 44 44 44 44 44 44 44]
184

So scipy is doing something screwy to Numeric....It looks like the fastumath 
module is not consistent with Numeric with respect to using a long for 
comparisions as opposed to the type (compare UBYTE_less in Numeric's 
umathmodule.c with that in scipy's fastumath_unsigned.inc, for instance).

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke                      http://arbutus.physics.mcmaster.ca/dmc/
|cookedm at physics.mcmaster.ca



More information about the SciPy-user mailing list