Eman Eman - 1 month ago 8
Bash Question

how to compute power value with bash shell

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"

Answer

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
Comments