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!

 채택된 답변

James Tursa
James Tursa 2011년 4월 21일

1 개 추천

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

Dillon Geo
Dillon Geo 2011년 4월 21일
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!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Chirag Gupta
Chirag Gupta 2011년 4월 21일

0 개 추천

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;
}

카테고리

도움말 센터File Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by