gravity121
gravity121

Reputation: 33

Python sum elements between two numbers

I'm sure this is very simple. I've searched google and here and not found the specific answer

a = rnd.randn(100)
print np.sum(a)

gives sum of elements in a

np.sum(a[a>0.])

gives sum of elements greater than 0

print np.sum((a < 2.0) & (a > -2.0))

ok so this returns the number of elements between 2 and -2.

how do I get the sum of the elements between2 and -2??? I've tried lots of things for example

np.sum(a[a >0.] & a[a<1.])

etc and can't find the correct way to do it :-(

Upvotes: 2

Views: 1695

Answers (2)

Adam Price
Adam Price

Reputation: 850

You could do it in just in a very basic direct way, something like:

function getSum(numArray, lowVal, highVal):
    mySum = 0
    for i in range(len(numArray)):
        if(numArray[i] >= lowVal and numArray[i] <= highVal):
             mySum = mySum + numArray[i]

    return mySum

yourAnswer = getSum(a, -2, 2)

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107287

& is a bitwise operator and doesn't give you the proper result, instead you need to use np.logical_and to get a mask array. Then you can pass it as the index to the array in order to get the desire items, then pass it to the sum:

In [9]: a = np.arange(-10, 10)

In [10]: a[np.logical_and(a>-2,a<2)]
Out[10]: array([-1,  0,  1])

In [11]: a[np.logical_and(a>-2,a<2)].sum()
Out[11]: 0

Upvotes: 4

Related Questions