how to compute power value with bash shell

bash, shell

Solution

Bash's built-in arithmetic only operates on integers, and doesn't allow a negative exponent for the `**` operator.

There are a variety of other tools available that can perform floating-point arithmetic. For example:

$ c=3.0
$ g=-3.0
$ awk "BEGIN{print $c ^ $c}"
27
$ awk "BEGIN{print $c ^ $g}"
0.037037
$ perl -e "print $c ** $c, qq(\n), $c ** $g, qq(\n)"
27
0.037037037037037

To store the result in a variable:

$ c=$(awk "BEGIN{print $c ^ $c}")
$ echo $c
27

In Awk, `^` is the exponentiation operator (which could be confusing to C programmers, since C's `^` operator is bitwise xor). Perl uses `^` for bitwise xor, like C, and `**` for exponentiation. GNU Awk (gawk) supports `**` as an exponentiation operator as an extension, but the use of that extension should be avoided in portable code.

Problem

We want to calculate 2^(3.0) and 2^(-3.0). thanks. ``` !/bin/bash c=3.0 g=-3.0 c=$((2**$c)) #syntax error: invalid arithmetic operator (error token is ".0") g=$((2**$g)) #syntax error: invalid arithmetic operator (error token is ".0") echo "c=$c" echo "g=$g" ```

Original source