Question

I am changing my program from floating-point precision to double precision. Nevertheless I start this routine by reading floating point numbers from a binary file.

bufz = alloc1float(nz);
for (i=0; i<nx; i++) {
    nu = efread(bufz,sizeof(float),nz,vel); 
    for (k=0; k<nz; k++)
        vn2[k][i] = bufz[k];
}

I proceed with calculations that shall be of double precision and write the calculated values into a file:

matlabfile=fopen("matlabfile","a+");
fprintf(matlabfile,"%d;%15.7e;%15.7e\n",l,amxs,amxr);
fclose(matlabfile);

(amxs and amxr are of size double, l is int and matlabfile is a filepointer)

My question: How does C proceed with the input parameters of type float when the arithmetic is done with double precision and how does it round the result in the output? Is it that easy as shown or do I miss something significantly?

EDIT: FILE *vel, *matlabfile;

 int main(int argc, char *argv[])
 {

 int i, nx, nz, k, nu, l;
 double amxs, amxr;
 double *buf;
 double **vn2;

 vn2    = alloc2double(nx,nz);
 buf = alloc1float(nz);

   /* read input binary file */
   for (i=0; i<nx; i++) {
    nu = efread(buf,sizeof(float),nz,vel); 
    for (k=0; k<nz; k++) vn2[k][i] = bufz[k];
   }

 Arithmetics with double precision arrays, variables and vn2...

// save output
matlabfile=fopen("matlabfile","a+");
fprintf(matlabfile,"%d;%15.7e;%15.7e\n",l,amxs,amxr);
fclose(matlabfile);
Was it helpful?

Solution

It doesn't. It (implicitly) converts the double into a float and you lose precision. It essentially chops off the least significant bits.

Sorry for the lack of concrete examples, but something like 9.223372036854775808 will become 9.223372037.

A similar thing happens when you load your floats into doubles. It converts them into a different format. EDIT... which works out fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top