bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Arithmetic pow results incorrect in arithmetic expansion.


From: Lawrence Velázquez
Subject: Re: Arithmetic pow results incorrect in arithmetic expansion.
Date: Sat, 9 Jan 2021 00:29:49 -0500

> On Jan 8, 2021, at 11:19 PM, Hyunho Cho <mug896@gmail.com> wrote:
> 
> Machine: x86_64
> OS: linux-gnu
> Compiler: gcc
> Compilation CFLAGS: -g -O2
> -fdebug-prefix-map=/build/bash-a6qmCk/bash-5.0=.
> -fstack-protector-strong -Wformat -Werror=format-security -Wall
> -Wno-parentheses -Wno-format-security
> uname output: Linux EliteBook 5.4.0-42-generic #46-Ubuntu SMP Fri Jul
> 10 00:24:02 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
> Machine Type: x86_64-pc-linux-gnu
> 
> Bash Version: 5.0
> Patch Level: 17
> Release Status: release
> 
> ####################################################################
> 
> i have tested below in gnome calculator, Qalculate, gawk, perl
> and all results in -4 but bash is 4
> 
> $ awk 'BEGIN { print -2 ^ 2 }'
> -4
> 
> $ perl -E 'say -2 ** 2'
> -4
> 
> $ echo $(( -2 ** 2 ))                     # only bash results in 4
> 4

The bash results disagree with awk and perl (and, admittedly, common
mathematical convention), but the man page clearly states that unary
minus has higher precedence than exponentiation, so this behavior
is intentional.

    The operators and their precedence, associativity, and values are
    the same as in the C language. The following list of operators is
    grouped into levels of equal-precedence operators. The levels are
    listed in order of decreasing precedence.

        id++ id--   variable post-increment and post-decrement
        - +         unary minus and plus
        ++id --id   variable pre-increment and pre-decrement
        ! ~         logical and bitwise negation
        **          exponentiation
        [remaining operators follow]

Additionally, this precedence is consistent with other shells.

    % bash --version | head -n 1
    GNU bash, version 5.0.17(1)-release (x86_64-apple-darwin18.7.0)
    % bash -c 'printf %s\\n "$((-2 ** 2))"' 
    4

    % ksh --version
      version         sh (AT&T Research) 93u+ 2012-08-01
    % ksh -c 'printf %s\\n "$((-2 ** 2))"'
    4

    % zsh --version
    zsh 5.8 (x86_64-apple-darwin18.7.0)
    % zsh -fc 'printf %s\\n "$((-2 ** 2))"'
    4
    % zsh -f -o C_PRECEDENCES -c 'printf %s\\n "$((-2 ** 2))"'
    4

The zshmisc(1) man page even goes out of its way to address this.

    Note the precedence of exponentiation in both cases is below that of
    unary operators, hence `-3**2' evaluates as `9', not `-9'. Use
    parentheses where necessary: `-(3**2)'. This is for compatibility
    with other shells.

I don't know why things shook out this way, but it sure seems like
the ship has sailed.

vq



reply via email to

[Prev in Thread] Current Thread [Next in Thread]