bashawkfloating-pointfloating-point-precisiongawk

awk read float precision: cannot read small floats, e.g. 4e-320


I cannot get awk or gawk to read small floats in scientific notation and interpret them correctly as floating point numbers.

I just want to output numbers above a small threshold with awk.

Example:

consider the following input:

4
3e-20
4.5e-320
3
1e-10

I want to threshold by 1e-15, so i do the following:

echo -e "4\n3e-20\n4.5e-320\n3\n1e-10"  |  awk '$1 > 1e-15'

which gives output:

4
4.5e-320
3
1e-10

Of course, 4.5e-320 does not pass the 1e-15 threshold, but awk and gawk fail to reject it!

I looked up (g)awk floating point precision. It seems to apply only to arithmetic operations within awk.

So, replacing awk '$1 > 1e-15' with gawk -v PREC="double" '$1 > 1e-15' also fails. It also fails with PREC="quad"

thus, I conclude that (g)awk is not reading 4.5e-320 as a float, but instead a string?


Solution

  • I get the expected output from awk version 3.1.5.

    I get your output from awk version 3.1.7.

    You can force awk to convert a string to a number by adding zero to it.

    So try this awk script instead:

    printf '4\n3e-20\n4.5e-320\n3\n1e-10\n' | awk '$1+0 > 1e-15'