problem of reading a double from .mat file in C
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
James Tursa
il 21 Apr 2011
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:
Più risposte (1)
Chirag Gupta
il 21 Apr 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;
}
0 Commenti
Vedere anche
Categorie
Scopri di più su Operators and Elementary Operations in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!