Search code examples
awkgnuplot

Reading variable with double float precision from a text file with gnuplot


I have a text file, containing data in 3 columns like below:

0.0100000000 0.0058077299 -0.0000000288
0.0110000000 0.0075128707 -0.0000000373
0.0120000000 0.0093579693 -0.0000000465

I want to get the variables from this file in gnuplot and use them to draw graphs:

What I exactly do is like below (e.g: to pick the variable from row 2 column 3):

ii  = 2
a_0 = system("awk '{ if (NR == " . ii . ") printf \"%f\", $3}' " .datafile)
a_0 = a_0+0.

but what is written as a_0 is zero!

How can I increase the precision to get the exact value?


Solution

  • The issue here is with the explicit way awk is instructed to read the number. When the precision is left out of the format specifier %.6f is assumed, thus awk returns 0.000000 for the number in the 3rd column on the 2nd line. You can fix this in a number of ways:

    1. Use a higher precision format specifier:

      a_0 = system("awk 'NR == ".ii." { printf \"%.10f\", $3 }' ".datafile)

      Note that there is implicitly a boolean expression at the head of each code-block in awk, so the if-statement is redundant here.

    2. Avoid numerical conversion in awk entirely:

      a_0 = system("awk 'NR == ".ii." { print $3 }' ".datafile)

    3. Use higher precision conversion by setting OFMT:

      a_0 = system("awk 'NR == ".ii." { print 0+$3 }' OFMT='%.10f' ".datafile)

      Further discussion about numerical conversion in awk can be seen in this answer I gave concerning a similar issue.

    The result of running print a_0 at the end of the script is in all cases:

    -3.73e-08