precision difference in matlab and gnu g++

5 Ansichten (letzte 30 Tage)
DavidK
DavidK am 3 Aug. 2012
Hi all,
I have two short code examples which do the same. One is written in matlab the other in c++.
The result in matlab code is -2.168404344971009e-19.
The result in c++ code is -3.01755e-20
The difference in results is much toooo huge! What can I do?
Thanks in advance!
--- matlab code start ---
w = -0.00161579
rho = -3.23158e-05
gamma = 0.02
Igrad = 0.0004
w = w - rho * gamma / Igrad
--- matlab code end ---
--- c++ code start ---
#include <iostream>
int main() {
double w = -0.00161579;
double rho = -3.23158e-05;
double Igrad = 0.0004;
const double gamma = 0.02;
w = w - rho * gamma / Igrad;
std::cout << w << std::endl;
}
--- c++ code end ---

Antworten (2)

Titus Edelhofer
Titus Edelhofer am 3 Aug. 2012
Hi,
not really: both answers are equally correct up to round off: the roundoff for the last difference is
eps(rho*gamma/Igrad)
which is in fact the answer MATLAB gives. Every answer that deviates from this by a maximum of 2.168e-19 is "correct".
Titus

DavidK
DavidK am 3 Aug. 2012
I'm confused as the mex-compiler of matlab is giving the correct result but g++ not.
C++ code "test.cc":
#include "mex.h"
#include <iostream>
void mexFunction(int nlhs, mxArray *plhs[], /* output */
int nrhs, const mxArray *prhs[]) /* input */
{
double w = -0.00161579;
double rho = -3.23158e-05;
double Igrad = 0.0004;
const double gamma = 0.02;
w = w - rho * gamma / Igrad;
std::cout << w << std::endl;
}
and matlab code main.m:
test();
Why is mex-c-compiler better than g++? Can I tune g++?
  2 Kommentare
Titus Edelhofer
Titus Edelhofer am 3 Aug. 2012
Again: everything in the interval [2* -2.168404344971009e-19 0] is equally correct.
Walter Roberson
Walter Roberson am 4 Aug. 2012
c++ does not use fixed-point arithmetic. c++ has the same roundoff problems that MATLAB has. It is possible, however, that in C++ the rounding mode is initialized differently.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu C Shared Library Integration finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by