problem of reading a double from .mat file in C
3 ビュー (過去 30 日間)
古いコメントを表示
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!
0 件のコメント
採用された回答
James Tursa
2011 年 4 月 21 日
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 件)
Chirag Gupta
2011 年 4 月 21 日
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;
}
0 件のコメント
参考
カテゴリ
Help Center および 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!