1

I have a file named "Q.csv" that is a text file containing:

-4.999118817962964961e-07 1.500000000000000197e-08 9.151794806638024753e-08 9.151794806638024753e-08

I'd like to read this as a 2x2 matrix into a C program. Currently my program looks like this.

 #include <stdio.h>
 #include <stdlib.h>
 int main(){
    FILE* inf;
    inf = fopen("Q.csv","r");
    int nrows = 2;
    int ncols = 2;
    double grid[nrows][ncols];
    double t;
    size_t x, y;
        for (x=0; x<ncols; ++x){
                for(y=0; y< nrows; ++y){
                        fscanf(inf,"%lg ",&t);
                        grid[x][y]=t;
                        printf("%lg\n",grid[x][y]);
                }
        }
        fclose(inf);
}

This program works. But it doesn't output all of the precision that was originally in Q.csv - for example, it outputs the first number as -4.99912e-07. If I take away the %lg and change it to %.18g, for example, it outputs the wrong thing. Same if I put %.18lg. In fact, both of these result in the mystery number 4.94065645841246544e-324 repeated (where is this coming from?!)

What can I do to get all of the precision in the file into C?

Samuel Reid
  • 145
  • 6
  • To help debug such problems, good idea to initialize `grid[][]` and to check the result value from `fscanf() == 1` – chux - Reinstate Monica Dec 07 '15 at 20:58
  • Perhaps your systems does not understand `l` in `printf("%lg\n",grid[x][y]);` which is not valid in older C. Try removing it. – chux - Reinstate Monica Dec 07 '15 at 20:59
  • The post says `CSV` (Comma Separated Values), yet text contents have no `','`. Does the post match the true text in`"Q.csv"`? – chux - Reinstate Monica Dec 07 '15 at 21:01
  • The post matches the true text in Q.csv, yes, but good point about the file type. Also I had checked the fscanf() == 1 condition and it was true, but I guess I forgot to mention that! All in all, thanks for a thorough analysis :) – Samuel Reid Dec 07 '15 at 21:13

1 Answers1

1

Input will be read with fscanf(inf,"%lg ",&t); as good as it can.

To print out with 18 digits after the decimal point, use

 printf("%.*le\n",18, grid[x][y]);

If double has sufficient precision, check value DBL_DIG which must be at least 10. I suspect double will only be good for 15-17 total digits.


To get all the precision, see Printf width specifier to maintain precision of floating-point value

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • Awesome, thanks for the quick and thorough answer. This worked perfectly. I actually got all the decimal with your code! – Samuel Reid Dec 07 '15 at 21:11