tags:

views:

53

answers:

1

Hi Everyone, Maybe this question should be strictly in the scipy-users, but I'll try here too.

So here is something which I discovered lately and is making me wonder.

I want to define a scalar which I call Net Absolute Mass Balance Error or in short NAMBE. This NAMBE is the absolute difference between a base vector and another vector, divided by the base vector and multiplied by a hundred, in pseudo-code notation:

NAMBE=sum(abs(a-b)/a)*100

When I do it in python, I decided to break the line into two lines so the code is more readable:

>>> a=np.array([0.1,0.1,0.1,0.1,0.1])
>>> b=np.array([0.1,0.1,0.1,0.1,0.1])*2
>>> b
array([ 0.2,  0.2,  0.2,  0.2,  0.2])
>>> a-b
array([-0.1, -0.1, -0.1, -0.1, -0.1])
>>> s=np.sum(abs(a-b))
>>> s
0.5
>>> s/np.sum(a)
1.0

I thought the numpy does everything element wise so if I do it one line, I noticed the the result is different:

>>> s=np.sum(abs(a-b)/a)
>>> s
5.0

Now If I check myself on the data I have with a octave, I get different results:

octave:1> a=[0.1,0.1,0.1,0.1,0.1]
a =

   0.10000   0.10000   0.10000   0.10000   0.10000

octave:2> b=a*2
b =

   0.20000   0.20000   0.20000   0.20000   0.20000

octave:3> sum(a)
ans =  0.50000
octave:4> sum(b)
ans =  1
octave:5> sum(a-b)
ans = -0.50000
octave:6> sum(abs(a-b))
ans =  0.50000
octave:7> s=sum(abs(a-b))
s =  0.50000
octave:8> s/sum(a)
ans =  1
octave:9> s=sum(abs(a-b)/a)
s =  1.0000
octave:10> s=sum(abs(a-b)/sum(a))
s =  1

Note that the is no difference in the output of 9 and 10 in Octave, although there is in Python ... So, my question is: Why is python is behaving like that ? Which one is right ? Octave or Python ?

+7  A: 

sum(a-b)/sum(a) is not the same as sum((a-b)/a).

Consider e.g. a=[1,0] and b=[-1,1]. Then sum(a/b) == sum([-1,0]) == -1, but sum(a)/(sum(b) == 1/0 which doesn't make sense.

katrielalex
When I tell you that b can only have positive values ? I should have mentions that before. I understand the argumentation, but I think numpy should in this case behave like Octave.
Oz123
Plus, I actually, tried your test case: here is the result: >>> import numpy as np>>> a=np.array([1,0])>>> b=np.array([-1,1])>>> np.sum(a)/np.sum(b)0 As you can see - it yield 0 and not Inf !!! Python in this case behaves in very unintuitive way, while octave gives: octave:1> a=[1,0]a = 1 0octave:2> b=[-1,1]b = -1 1octave:3> sum(a)/sum(b)warning: division by zeroans = Inf
Oz123