Tanmoy Chakraborty
Tanmoy Chakraborty

Reputation: 45

Bash calculator

The following line is not working in my script:

a=$(echo "scale=3;(2*$j/(sqrt(3)*$i))" | bc)
a1=$(echo `expr "scale=3; $a^(1/3)"` | bc -l)

The error it is giving:

Runtime warning (func=(main), adr=21): non-zero scale in exponent

I just want to have the value of cube root of 'a'. Somehow, I am not getting it. Please give some idea.

Upvotes: 1

Views: 3661

Answers (2)

fedorqui
fedorqui

Reputation: 289675

You probably want to use awk for this instead of using complex bc syntaxs:

awk -v num=$bash_variable 'BEGIN{print num^(1/3)}'

For example:

v=3
awk -v num=$v 'BEGIN{print num^(1/3)}'

Returns: 1.44225.

Or store the variable for a further usage:

var=$(awk -v num=$v 'BEGIN{print num^(1/3)}')

Upvotes: 1

anubhava
anubhava

Reputation: 785128

This line is problematic:

a1=$(echo `expr "scale=3; $a^(1/3)"` | bc -l)

Since you cannot use a non-integer value as a power in bc.

Example to reproduce this error:

bc -l
bc 1.06
sqrt(3)^(1/3)
Runtime warning (func=(main), adr=11): non-zero scale in exponent
1

Solution:

You can use this function to calculate cube root:

a1=$(bc -l <<< "scale=3; e(l($i)/3)")

Example:

i=8; bc -l <<< "scale=3; e(l($i)/3)"
1.999

Or use awk as mentioned by @fedorqui

Upvotes: 2

Related Questions