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

Re: arithmetic operator precedence



On Tue, Jun 17, 2008 at 12:24:12PM +0200, Richard Hartmann wrote:
> On Tue, Jun 17, 2008 at 11:45, Stephane Chazelas
> <Stephane_Chazelas@xxxxxxxx> wrote:
> 
> 
> > In which way is it more "mathematically" correct?
> >
> > Is that because -3² is -9?
> >
> > But ** is not ^, it's a binary operator whose shape reminds that
> > of multiply, like a multiply++. And even then, POSIX's ^ in bc
> > is handled as -3^2 = 9.
> 
> As far as I know, ^ and ** are fuly equivalent. If that is not the case, then
> sorry. Do you have a link/manpage/whatever on this topic?
[...]

Not sure what you mean. ^ in bc is the power operator and
there's no ** there. In shells, ** is the power operator and ^
is the XOR operator.

What I meant is that ^ reminds of the /human/ (as opposed to
/computer/) representation as it indicates that follows must be
raised up as in 3². So, one can understand that it should follow
the same rules (that is -3^2 should be the same as -3², even
though that's not what POSIX decided for bc). But given that **
has more the shape of the * operator, I'm not sure we can tell
the same thing.

Anyway, I was just curious about Peter's statement. I'm most
probably not as versed in maths as he is, so was curious about
the rationale behind his statement about -3**2 = 9 not being
mathematically correct.

Looking at bc history, it seems to have appeared in Unix V6
(1975), and it was a wrapper written in yacc around dc (a
reverse polish calculator: _3 2 ^ is less ambiguous there). I'm
not versed enough in yacc or grammars to tell whether the
precedence was the same, but you can have a look at:

http://minnie.tuhs.org/UnixTree/V6/usr/source/s1/bc.y.html

 %right '='
 %left '+' '-'
 %left '*' '/' '%'
 %right '^'
 %left UMINUS
[...]
 e       :  e '+' e
                 = bundle( $1, $3, "+" );
         |  e '-' e
                 = bundle( $1, $3, "-" );
         | '-' e         %prec UMINUS
                 = bundle( " 0", $2, "-" );
         |  e '*' e
                 = bundle( $1, $3, "*" );
         |  e '/' e
                 = bundle( $1, $3, "/" );
         |  e '%' e
                 = bundle( $1, $3, "%%" );
         |  e '^' e
                 = bundle( $1, $3, "^" );
[...]

-- 
Stéphane



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