# Shell Scripting: calculate power of a number with a real number as an exponent

I am using shell scripting and I am using the following expression:

``````A=`echo "(( ((\$a / \$b) ^ 0.3) -1 ))" |bc -l`
``````

I want to have a real number as an exponent. I noticed that If I place 0.3, it rounds off to an integer and takes the power of zero. Similarly if I use 5.5 or 5.9 in place of 0.3 in the above expression, I get the same answer.

How do I calculate the power of a number with the exponent being a real number and not an integer

• Do you get a `non-zero scale in exponent` error? if so, it's a limitation of `bc` I think: see for example Using fractional exponent with bc – steeldriver Jan 30 '16 at 0:05
• It just uses the integer value and not the real number. with 5.5 it will take the exponent of 5. Similarly with 0.3 it will take the exponent of 0 – Syed Moez Jan 30 '16 at 0:09
• You could try `A=`echo "( e(0.3 * l(\$a / \$b)) -1 )" | bc -l` ` – steeldriver Jan 30 '16 at 0:17

Why can't you use awk or perl one-liner to handle it?

``````echo "\$a \$b" | awk '{ print (((\$1/\$2)^0.3) -1); }'
``````

You cannot directly use the `^` operator to raise to a non-integer exponent, however, you can use the identity

ab = eln(a) × b

with `e` being the base of the natural logarithm. `bc`, when called with the `-l` option, has the functions `e` and `l` to compute base-`e` exponentiation and the natural logarithm respectively, so in order to compute `a^b` you just write `e(l(a)*b)`.

For example, for 20.5 (square root of 2):

``````\$ echo 'e(l(2)*0.5)' | bc -l
1.41421356237309504878
``````

I'm afraid you can't use `bc` for that. It doesn't support floating point exponents. As explained in `man bc`:

expr ^ expr

The result of the expression is the value of the first raised to the second. The second expression must be an integer. [ ... ]

So, you'll have to use something else such as `awk`:

``````awk -va="\$a" -vb="\$b" 'BEGIN{print ((a/b)^0.3)-1}'
``````

or, as suggested by Dennis Jacob:

``````echo "\$a \$b" | awk '{print (((\$1/\$2)^0.3) -1);}'
``````

Or `perl`:

``````perl -le 'print (((\$ARGV[0]/\$ARGV[1])**0.3)-1)' "\$a" "\$b"
``````

or

``````echo "\$a \$b" | perl -lane 'print (((\$F[0]/\$F[1])**0.3) -1)'
``````

You can use r instead of bc:

``````A=\$(echo "x=( ( (\$a / \$b) ** .3 ) -1 );print (x)" | r)
``````

but of course more programming languages can solve this.