[SciPy-User] Order of numpy orperations is not equal to logic (and also octave)?

David Cournapeau cournape@gmail....
Sun Oct 31 03:48:49 CDT 2010


On Sun, Oct 31, 2010 at 5:34 PM, Oz Nahum Tiram <nahumoz@gmail.com> wrote:
> Hi Everyone,
>
> 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)

This is indeed different than the first line, because you are
computing two different things. In numpy, every basic arithmetic
operation is *element*-wise. So you have you have two vector x and y,
x / y will compute x[0]/y[0], etc...

abs(a-b)/a is the vector (a[0]-b[0])/a[0], ...., (a[4]-b[4])/a[4].

>
>
>>>> 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 ?

Neither is right or wrong - they both use different definitions of
some operators (here /). I am not sure what abs(a-b)/a does in octave,
though

David


More information about the SciPy-User mailing list