[SciPy-user] summation of array elements
Travis E. Oliphant
oliphant at ee.byu.edu
Wed Jun 30 14:06:40 CDT 2004
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.
In general, there should be no need to import Numeric separately and if
you do you run the risk of little buglets like this. One thing SciPy
tries to do is subsume your usage of Numeric (except for the experts)
so that a simple
from scipy import *
should suffice.
Here is the reworked code (notice you don't need to separately call
RandomArray which was the source of the problem)
from scipy import *
nx,ny = 100,10
def gen_lattice(nx,ny,c):
x = stats.uniform.rvs(size=(nx,ny))
return (x < c)
c = 1
x = gen_lattice(nx,ny,c)
print sum(x)
print sum(ravel(x))
>
> One would expect an output of ten 100s and a 1000 but instead of the
> 1000 it prints 232. Does anybody have a idea whats wrong?
>
> To anticipate corresponding questions, normally I also want to vary c
> between 0..1 ;-)
>
> Thank you for your help!
> Ciao by Philipp
>
>
> _______________________________________________
> SciPy-user mailing list
> SciPy-user at scipy.net
> http://www.scipy.net/mailman/listinfo/scipy-user
More information about the SciPy-user
mailing list