0

I am facing problem in comparing big floating variables in unix

Code: error message: syntax error on line 1 teletype I got to know from one of the old posts in the forum this is because "the script is trying to do a calculation with bc by echoing an expression into it. But one of the variables has an illegal number"

Below is the script which is giving the error

Code:

#! /bin/bash -xv
a=`cat abc.csv  | sed '1d' | tr -s ' ' | cut -d, -f3`
echo $a 
-180582621617.24

b=`sed '1d' def.csv | cut -d',' -f7 | awk '{s+=$1}END{ printf("%.2f\n",s)}'`
echo $b
-180582621617.37

Result=`echo "if($a !=$b) 1" | bc `

if [ $Result -eq 1 ]; then
echo "both values not equal"
else
echo " both values equal"
fi

But I was able to compare it when hard-coded

Code:

a=`echo "-180582621617.24,222.555,333.333" | awk -F"," '{print $1}'`
b=`echo "-180582621617.24,222.555,333.333" | awk -F"," '{print $1}'`

Result=`echo "if($a !=$b) 1" | bc `

if [ $Result -eq 1 ]; then
echo "both values not equal"
else
echo " both values equal"
fi
fedorqui
  • 275,237
  • 103
  • 548
  • 598
karthik adiga
  • 133
  • 2
  • 12
  • But you *do* know that comparing floats for equality is a seriously stupid idea to begin with? Do you know that 10 times 0.1 is hardly ever 1? – Jens Jan 23 '15 at 14:40

3 Answers3

1

Your test in bc is return 1 if true and nothing when false.

$Result will be then either undefined or numeric (1). test with -eq only works with two operands both numeric. Just return 0 for the else case

Result=`echo "if($a !=$b) 1 else 0" | bc `
if [ $Result -eq 1 ] ; then
    echo "both values not equal"
else
    echo " both values equal"
fi
Matteo
  • 14,696
  • 9
  • 68
  • 106
0

Use bc for dealing with floating numbers in shell:

$ bc <<< '-180582621617.24 == -180582621617.37'
0
$ bc <<< '-180582621617.24 != -180582621617.37'
1

In your case, it is going to be bc <<< "$a != $b", e.g.:

[[ bc <<< "$a != $b" ]] && Result=1 || Result=0
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • But this is what he is doing: `Result=`echo "if($a !=$b) 1" | bc ` – Matteo Jan 23 '15 at 13:46
  • But it works (and the OP also shows a second example where it works). The syntax error is not due to piping the command to bc – Matteo Jan 23 '15 at 13:51
0

Thanks for all the suggestions.

I was able to compare by creating two temp files and using the diff -w command.

#! /bin/bash -xv
rm -f triger_cksum.txt data_cksum.txt
a=`cat ab.csv | sed '1d' | tr -s ' ' | cut -d, -f3`
echo $a > triger_cksum.txt
b=`sed '1d' cd.csv | cut -d',' -f61 | awk '{s+=$1}END{ printf("%.6f\n",s)}'`
echo $b > data_cksum.txt
diff_files=`diff -w triger_cksum.txt data_cksum.txt | wc -l | tr -s ' '`
if [ $diff_files -eq 0 ]
then
echo "cksum equal"
else
echo "cksum not equal"
fi
Pang
  • 9,564
  • 146
  • 81
  • 122
karthik adiga
  • 133
  • 2
  • 12