Hi,
I'm having a problem with comparisons and floating point arithmetic in awk. Some very simple comparisons don't give the correct answer.
I've created a simple script to attempt to find the cause of the problem. The script loops through a range of floating point numbers, and performs a comparison. The results of the script are as follows:
0.02 = 0.01 + 0.01
0.03 = 0.01 + 0.02
0.04 = 0.01 + 0.03
0.05 = 0.01 + 0.04
0.06 != 0.01 + 0.05 (FAIL)
0.07 != 0.01 + 0.06 (FAIL)
0.08 = 0.01 + 0.07
0.09 = 0.01 + 0.08
0.1 != 0.01 + 0.09 (FAIL)
0.11 = 0.01 + 0.1
0.12 = 0.01 + 0.11
0.13 = 0.01 + 0.12
0.14 = 0.01 + 0.13
0.15 != 0.01 + 0.14 (FAIL)
0.16 = 0.01 + 0.15
0.17 = 0.01 + 0.16
0.18 != 0.01 + 0.17 (FAIL)
0.19 = 0.01 + 0.18
0.2 = 0.01 + 0.19
0.21 != 0.01 + 0.2 (FAIL)
0.22 = 0.01 + 0.21
0.23 = 0.01 + 0.22
0.24 != 0.01 + 0.23 (FAIL)
0.25 = 0.01 + 0.24
0.26 = 0.01 + 0.25
0.27 = 0.01 + 0.26
0.28 = 0.01 + 0.27
0.29 != 0.01 + 0.28 (FAIL)
.. and this is the script..
#! /bin/ksh93
vat=0
net=0.01
while [ $vat -lt 11 ]
do
(( vat = $vat + 0.01 ))
(( total = $net + $vat ))
printf "$total\t$net\t$vat\t" > /tmp/x.tmp
result=`awk -F" " '
{
v_total = $1
v_net = $2
v_vat = $3
if ( v_total == v_net + v_vat ) {
output=v_total " = " v_net " + " v_vat }
else {
output=v_total " != " v_net " + " v_vat " (FAIL)" }
}
END { print output }
' /tmp/x.tmp`
echo $result
done
done
I'd really appreciate any advice anyone could give. This problem is driving me crazy.
Thanks,
Kevin
I'm having a problem with comparisons and floating point arithmetic in awk. Some very simple comparisons don't give the correct answer.
I've created a simple script to attempt to find the cause of the problem. The script loops through a range of floating point numbers, and performs a comparison. The results of the script are as follows:
0.02 = 0.01 + 0.01
0.03 = 0.01 + 0.02
0.04 = 0.01 + 0.03
0.05 = 0.01 + 0.04
0.06 != 0.01 + 0.05 (FAIL)
0.07 != 0.01 + 0.06 (FAIL)
0.08 = 0.01 + 0.07
0.09 = 0.01 + 0.08
0.1 != 0.01 + 0.09 (FAIL)
0.11 = 0.01 + 0.1
0.12 = 0.01 + 0.11
0.13 = 0.01 + 0.12
0.14 = 0.01 + 0.13
0.15 != 0.01 + 0.14 (FAIL)
0.16 = 0.01 + 0.15
0.17 = 0.01 + 0.16
0.18 != 0.01 + 0.17 (FAIL)
0.19 = 0.01 + 0.18
0.2 = 0.01 + 0.19
0.21 != 0.01 + 0.2 (FAIL)
0.22 = 0.01 + 0.21
0.23 = 0.01 + 0.22
0.24 != 0.01 + 0.23 (FAIL)
0.25 = 0.01 + 0.24
0.26 = 0.01 + 0.25
0.27 = 0.01 + 0.26
0.28 = 0.01 + 0.27
0.29 != 0.01 + 0.28 (FAIL)
.. and this is the script..
#! /bin/ksh93
vat=0
net=0.01
while [ $vat -lt 11 ]
do
(( vat = $vat + 0.01 ))
(( total = $net + $vat ))
printf "$total\t$net\t$vat\t" > /tmp/x.tmp
result=`awk -F" " '
{
v_total = $1
v_net = $2
v_vat = $3
if ( v_total == v_net + v_vat ) {
output=v_total " = " v_net " + " v_vat }
else {
output=v_total " != " v_net " + " v_vat " (FAIL)" }
}
END { print output }
' /tmp/x.tmp`
echo $result
done
done
I'd really appreciate any advice anyone could give. This problem is driving me crazy.
Thanks,
Kevin