1

In bash script, I have 1 script like this:

n1 = 1
n0 = 59

# compute p1
p1=$((n1/n0))
echo "p1 = $p1"

I'd like my output is p1 = 1/59 = 0.016949153 but reality, output is p1 = 0

So, How to fix it. help me please

TrungTrung
  • 33
  • 1
  • 8
  • [tag:bash] cannot handle floats. You could multiply it by e.g. 1000 if you want a precision of 3 decimals and then print it accordingly. Better to use [tag:awk] though. – pfnuesel Nov 25 '13 at 09:38

3 Answers3

5

BASH doesn't do any floating point maths. You can either use bc or awk for that.

For ex::

p1=$(bc -l <<< "scale=5; $n1/$n0")
echo "$p1"
.01694

UPDATE: Using awk:

awk -v n1=$n1 -v n0=$n0 'BEGIN{printf("%.5f\n", (n1/n0))}'
0.01695
anubhava
  • 761,203
  • 64
  • 569
  • 643
2

You can use bc to get arbitrary precision maths:

pax> n1=355 ; n0=113
pax> p1=$(echo "scale=50;$n1/$n0" | BC_LINE_LENGTH=9999 bc) ; echo $p1
3.14159292035398230088495575221238938053097345132743

The line length stops bc from doing its annoying line break behaviour for longer results.

If you have a more reverse polish mindset like me, you can also use dc:

pax> n1=355 ; n0=113
pax> echo 50 k $n1 $n0 / p | dc
3.14159292035398230088495575221238938053097345132743

In both cases, you can set the scale to be used (by setting scale in bc or using the k command in dc).

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
2

I'd like to add

p1=$(python -c "print $n1*1.0/$n0")
glglgl
  • 89,107
  • 13
  • 149
  • 217