Quantcast
Channel: Question and Answer » gawk
Viewing all articles
Browse latest Browse all 13

awk floating point arithmetic – surprising result

$
0
0

I’ve been trying to get awk to do some trivial arithmetic, which involves carrying some values from one line to the next.

Here is a minimal example pair, for comparison.
The first example is expected behaviour, since 99.16 – 20.85 = 78.31

$ echo -e "0,99.16n20.85,78.31" | awk -F, '{
  if (NR != 1 && (prior_tot - $1) != $2) {
    print "Arithmetic fail..." $0
  } else {
    print "OK"
  };
  prior_tot = $2
}'

Returns

OK
OK

The second example is not expected behaviour, since 99.15 – 20.85 = 78.30

$ echo -e "0,99.15n20.85,78.30" | awk -F, '{
  if (NR != 1 && (prior_tot - $1) != $2) {
    print "Arithmetic fail..." $0
  } else {
    print "OK"
  };
  prior_tot = $2
}'

Returns

OK
Arithmetic fail...20.85,78.30

Can anybody explain what is going on here?


Viewing all articles
Browse latest Browse all 13

Trending Articles