x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 298

# Bash Calulation

HI,

I have a bash script and need to do a calculation and return an integer.
The issue I have is expr and bc don't deal with decimal exponents.

This is the excel equation I am trying to get working in bash.

Does anyone know how to do this in bash and just return the rounded down value?
All decimal answers should be rounded down.

Thanks
Fixitben
0
fixitben
1 Solution

Commented:
echo \$START \$CPU | awk '{printf "%d", \$1*\$2^0.422}'

or, to use the variables inside awk and to avoid "echo"

1)
awk 'BEGIN {printf "%d", '\$START'*'\$CPU'^0.422}'

2)

awk -v S=\$START -v C=\$CPU 'BEGIN {printf "%d", S*C^0.42}'

wmp
0

Commented:
The full statement

ANSWER=\$(awk -v S=\$START -v C=\$CPU 'BEGIN {printf "%d", S*C^0.42}')
0

Author Commented:
That worked great. Thanks
0

Commented:
bc is a command that does just that.  If you do not specify the 'scale' to give it the number of decimal point places to use then it assumes no places and rounds down to the nearest integer.

Now the next step.  You can't do 'to the power of' in bc with a real number.  The value to the right has to be an integer.  Its just not going to handle that.

You'll need to convert it first.  Get your maths text book out and look up :
x^y = e^(y*log(x))
This is an alternative way of working out x^y and can  be handled by bc.
I've never done this part so you'll have to play round with it.
0

``````START=1.5
CPU=2
echo "e(0.477*l(\${START}*\${CPU}))" | bc -l
1.68883351312073475842
``````

and rounded:

``````START=1.5
CPU=2
echo "e(0.477*l(\${START}*\${CPU}))" | bc -l | xargs printf "%1.0f\n"
2
``````
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.