Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: arithmetic operator precedence



On 2008-06-16 14:59:34 +0100, Stephane Chazelas wrote:
> It's at least consistent with other shells and bc at the moment:
> 
> ~$ bash -c 'echo $((-2**2))'
> 4
> ~$ zsh -c 'echo $((-2**2))'
> 4
> ~$ ksh93 -c 'echo $((-2**2))'
> 4
> ~$ echo '-2 ^ 2' | bc
> 4

That are almost the only ones.

> bc is one place where POSIX specifies the precedence of
> unary-minus vs power:
> http://www.opengroup.org/onlinepubs/009695399/utilities/bc.html
> minus has higher precedence than ^ which I have to say is more
> intuitive to me.

Most users find the other way more intuitive, as with conventional
math writing

    2
  -2  = -4

(and that's also the reason why ** is right-associative, whereas
most operations are left-associative).

> Having said that:
> 
> ~$ perl -le 'print -2 ** 2'
> -4
> ~$ python -c 'print -2 ** 2'
> -4
> ~$ ruby -e 'print -2 ** 2'
> -4%
> ~$ gawk 'BEGIN {print -2 ** 2}'
> -4

and:

vin:~> calc -- '-2 ^ 2'
        -4
vin:~> qalc '-2 ^ 2'
-(2^2) = -4
vin:~> wcalc '-2 ^ 2'
 = -4
vin:~> echo '-2 ^ 2' | gp -q
-4
vin:~> echo '-2 ^ 2;' | maple -q
                                      -4
vin:~> echo '-2 ^ 2; quit' | mupad -S
>> -2 ^ 2; quit

                                    -4

-- 
Vincent Lefèvre <vincent@xxxxxxxxxx> - Web: <http://www.vinc17.org/>
100% accessible validated (X)HTML - Blog: <http://www.vinc17.org/blog/>
Work: CR INRIA - computer arithmetic / Arenaire project (LIP, ENS-Lyon)



Messages sorted by: Reverse Date, Date, Thread, Author