About a shell script

echo "Enter three integers with space between"
read a b c
sum=`expr $a + $b + $c `
mean=`expr $sum / 3 `
d1=`expr $a - $mean `
d2=`expr $b - $mean `
d3=`expr $c - $mean `
s1=`expr $d1 \* $d1 `
s2=`expr $d2 \* $d2 `
s3=`expr $d3 \* $d3 `
sd1=`expr $s1 + $s2 + $s3 `
sd1=`expr $sd1 / 3`
d=$(echo "sqrt($sd1)" | bc)
echo Sum=$sum
echo mean=$mean
echo standard deviation=$d

Why standard deviation is not calculated here

@Sneha , welcome, does the following work for you ?

echo "Enter three integers with space between"
read a b c 
sum=$(bc -l <<<" $a + $b + $c")
mean=$(bc -l <<<" $sum / 3") 
d1=$(bc -l <<<" $a - $mean")
d2=$(bc -l <<<" $b - $mean")
d3=$(bc -l <<<" $c - $mean")
s1=$(bc -l <<<" $d1 * $d1")
s2=$(bc -l <<<" $d2 * $d2")
s3=$(bc -l <<<" $d3 * $d3")
sd1=$(bc -l <<<" $s1 + $s2 + $s3")
sd1=$(bc -l <<<" $sd1 / 3") 
d=$(bc -l <<<"sqrt($sd1)")
echo Sum=$sum
echo mean=$mean
echo standard deviation=$d
~                             
1 Like

bc -l is the key point here (and rounding error in $sd1 / 3)

$ echo 10/3 | bc
3
$ echo 10/3 | bc -l
3.33333333333333333333

Using a here document you can do everything in bc:

echo "Enter three integers with space between"
read a b c
bc -l << _EOT_
a=$a; b=$b; c=$c
sum=a+b+c
mean=sum/3
d1=a-mean
d2=b-mean
d3=c-mean
s1=d1*d1
s2=d2*d2
s3=d3*d3
sd1=s1+s2+s3
sd1=sd1/3
d=sqrt(sd1)
"Sum=";sum
"mean=";mean
"standard deviation=";d
_EOT_

In bc references to bc variables are just var
While $var is the reference of a shell variable. The unquoted here document allows $-substitution.

2 Likes

another possible ... do it all in bc

cat bc.input
a=read()
b=read()
c=read()
sum=a + b + c
mean=sum / 3
d1=a - mean
d2=b - mean
d3=c - mean
s1=d1 * d1
s2=d2 * d2
s3=d3 * d3
sd1=s1 + s2 + s3
sd1=sd1 / 3
d=sqrt(sd1)
print "Sum=", sum, "\n"
print "mean=", mean, "\n"
print "standard deviation=", d, "\n"
quit

echo 3 4 5 | bc -q -l bc.input
Sum=12
mean=4.00000000000000000000
standard deviation=.81649658092772603272
1 Like

@Sneha And to answer exactly "Why" from original post - this is because expr by default/design works with integers only, everything after (and including) the decimal point is simply truncated.

1 Like