problem of reading a double from .mat file in C

Hi All,
I have a .mat file named "test.mat" which contains an array D=[1,0.2]. I wrote a C program to read the second element (0.2) into a double variable x, and then to store 1000*x into another int variable n. My code follows:
double x;
int n;
pmat = matOpen("test.mat", "r");
pa = matGetVariable(pmat, "D");
x = *(mxGetPr(pa) +1);
cout << "x = " << x << endl;
n = (int)(1000*x);
cout << "n = " <<n << endl;
mxDestroyArray(pa);
return 0;
Surprsingly, the output is:
x = 0.2
n = 199
Why n is 199 instead of 200? What may be the cause?
Many Thanks!

 Réponse acceptée

James Tursa
James Tursa le 21 Avr 2011

1 vote

n = (int)(1000*x) is truncating the expression instead of rounding it, and your 0.2 is probably slightly less than 0.2 (since 0.2 can't be represented exactly in floating point). Try using num2strexact on x and on 1000*x to see what their exact decimal representation is. You can find num2strexact here:

1 commentaire

Dillon Geo
Dillon Geo le 21 Avr 2011
Thanks to James Tursa and Chirag Gupta.
I am also suspecting it is related to the way a floating number is stored. I used round() to eliminate this problem, and it seems working well.
I just did another experiment. I examined the meomry content of a new double variable X=1000*x (x still get its value from .mat file), and the memory content of another double variable Y which is assigned a value of 200 in C. Their memory contents ARE different, HOWEVER, they both print out as 200, either via cout or printf("%f"). Really hard to catch such a problem!

Connectez-vous pour commenter.

Plus de réponses (1)

Chirag Gupta
Chirag Gupta le 21 Avr 2011
It might be something to do with precision and and how the floating number was stored. On my MATLAB (R2011a) on mac (64 bit), I get: x =0.2000 n =200
My code is as follows:
#include <stdio.h>
#include "mat.h"
int main()
{
MATFile *pmat;
double x;
mxArray *pa;
int n;
pmat = matOpen("test.mat", "r");
pa = matGetVariable(pmat, "D");
x = *(mxGetPr(pa) +1);
printf("\nx=%lf",x);
n = (int)(1000*x);
printf("\nn = %d\n",n);
mxDestroyArray(pa);
return 0;
}

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by