简体   繁体   中英

Floating Point Error

I have a strange error in my C++ Code:

float cosTheta = someFunction();
cout << cosTheta << endl;  // prints 1 on the console
if (cosTheta == 1) {       // doesn't enter this condition
    cout << "it is 1" << endl;
}
float sinTheta = sqrt(1 - pow(cosTheta, 2));
return (someVariable * sinTheta);

The problem is: cosTheta is 1, but it does not enter the condition, although it prints 1 on the screen. When I print the returned Value, it should be 0, because cosTheta is 1, so sinTheta gets 0 and the return value gets 0, but I get 0.0953562...

I tested the same code in Java and there I get 0 as a result.

You shouldn't compare floating point numbers with == . Rounding errors in floating-point operations mean that you should choose a precision EPSILON (adequated to your case) and use it like this:

const float EPSILON = 0.00001;

if( fabs(cosTheta - 1) < EPSILON ) {
    cout << "It is approximately 1\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM