Help me please

Hi, I have problem with the values that are gained from MATLAB and C++.
First I run this program in C++ and I got the value of 4.469996e-6 for "tmass" in the program, but when I run the same equation in MATLAB it gives me the value of 4.58915E-06 and this is like what I have with my calculator and I don't know where the problem is, please help me.

#include <math.h>
#include <stdio.h>
double tmass, TH,x0, x1, x2, x3, x4;
int main(void)
{
x0=4378.537279;
x1=82265.022270;
x2=15.455161;
x3=64.726071;
x4=939.386425;
TH=100;
tmass = (TH * x0 * x0 * 0.000001*0.000001*0.000001) * 2330+(13/35)*4*((x0+x4)*TH*x3*2330)*0.000001*0.000001*0.000001+4*x3*TH*50*2330*0.000001*0.000001*0.000001;

printf(" tmass= %e x0= %f x1= %f x2= %f x3= %f x4= %f a=%f\n", tmass, x0, x1, x2, x3, x4);
}
Last edited on
There is an error in floating point arithmetics. Although 10-7 seems a bit much, I don't think there can be another reason.
Perhaps MATLAB uses actual fractions for this..
Do you think that this difference of 10-7 is important?
The problem is that a computer cannot exactly represent every decimal number. They can give you nothing better than a good approximation.

http://floating-point-gui.de/
Thanks for your reply but this is a part of a big program and this is important for me to calculate this value as accurate as possible so i need the exact solution if possible
thanks alot
If you want the exact solution, do it on paper. Your PC cannot provide exact floating point calculations.

Alternatively, remove all the decimal points and do the whole thing as integer calculations, and then put the decimal point back in afterwards. This will require you to think about the numbers.
It can be done with a library that handles more accurate calculations, such as GNU's MP Bignum library at http://gmplib.org/ I've never used it, but I hear it's what most people use for arbitrarily accurate calculations.
You can already try to use long double instead of double, and use the precise floating point model (in case you compiler provides such an option).

Also, in the parts with the constants, you might want to try to precalculate them by hand. For example, the (13/35) will probably do an integer division, and return 0 instead of 0.37xxxxx
"For example" ?
I didn't notice that at all. This is probably the source or your problem. Make it 13.0/35.
Tried it, you get 4.58e-6 with (13.0/35)
Thanks every one the problem solved successfully with your suggestions
Topic archived. No new replies allowed.