Identical math operations in C++ and matlab differ by ~1% (10^11 in this case!)
Show older comments
Hello,
I have a single (VERY LONG) line of code written in both C++ and matlab that evaluates a mathematical expression. The expression is just under 31,000 characters long, so it's pretty darn complicated.
When I evaluate this expression in matlab vs. C++ I get very different numbers:
MATLAB: 31856235311612.7
C++: 31745938896594.422
However, as you'll probably notice, they're not different enough to think I made a mistake in the transfer. I basically just copied and pasted the expression from C++, so no issues there.
I have two similar expressions of lower order that I also ported; one on the order of 10^9 (differs by about 1%), and one of order 10^7 which does not suffer the same magnitude of error:
MATLAB=3087973.34551207
C++=3087973.3455120716
The question is, which is "correct", and from where are these differences arising? I'm happy to provide code, but the first entry code is a 31,000 character expression!
FYI, in C++ all variables are stored as doubles.
Accepted Answer
More Answers (1)
James Tursa
on 29 Oct 2011
1 vote
Differences can arise from different order of operations, temporary results done in 80-bit vs 64-bit arithmetic, different rounding modes, etc, etc. As for which one is "correct", maybe neither is. Unless you examine the expression in detail to look for cancellation error etc who knows? How the heck do you expect to debug a 31000 character expression? I doubt anyone on this site will be willing to do so for you.
2 Comments
M S
on 29 Oct 2011
James Tursa
on 1 Nov 2011
Just because you copied the same expression from C++ to MATLAB does *not* guarantee that there are no order of operation differences. That was the point of my comment ... the compiler might be reordering things around without you being aware of it.
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!