Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Numeric comparisson with AWK 4

Status
Not open for further replies.

robdon

Programmer
May 21, 2001
252
ES
Hi,

I'm having a problem with awk (running on Tru64 5.1)

I have the following 'example' script

{
val3 = 16.775 * 100;

print "val3:" val3;

if (val3 == 1677.5)
print "match";

}

Now for some reason, I never get the 'match' text printed out.

Even though I know that val3 is 1677.5, the IF statement at the end does not seem to be true for some reason.

If I put in 'var3 = 1677.5' before the IF statement, then the IF works.

Can anyone explain what is going on , and why the IF statement does not return true?

Thanks for any help,

Rob Donovan


ProIV Resource Centre <a href='
 
Floating point numbers are approximations, which usually end up with rounding errors of one sort or another.

Which basically means that computed answers differ in some way from mathematical answers.

Code:
$ awk 'BEGIN { a=16.775; a=a*100; print a, a==1677.5 ; printf("%30.15f\n",a) }'
1677.5 0
          1677.499999999999773
Sure, the answer is close, but not close enough to satisfy an == test.

--
 
So a solution is to check how close the values match:

{
epsilon = 0.000000001

val3 = 16.775 * 100;

print "val3:" val3;

if (abs(val3 - 1677.5) <= epsilon)
print "match";

}

you probably need to define function abs() yourself:

function abs(val)
{
if (val > 0)
return val;
else
return -val;
}



HTH,

p5wizard
 
You could force awk to perform a string comparision :)
Code:
$ awk 'BEGIN { a=16.775; a=a*100; print a, a==1677.5, a""=="1677.5" }'
1677.5 0 1


The functional approach is going to be better in the long run.
Combining previous answers...
Code:
function abs( v )
{
  return v >= 0  ?  v  :  -v
}
function approxEqual( x, y )
{
  epsilon = 0.000000001
  return abs(x-y) <= epsilon
}

So you would then have
Code:
{
val3 = 16.775 * 100;

print "val3:" val3;

if ( approxEqual(val3,1677.5) )
  print "match";
}

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top