سؤال

I got really annoying problem that I can't solve. I've got this code fragment:

LOG(INFO) << "totalTranslation: " << m_move.totalTranslation << " tileSize: " << static_cast<double>(tileSize);
if(m_move.totalTranslation >= static_cast<double>(tileSize)) {
    LOG(INFO) << "in!";
}

tileSize equals 62 (it's int). In a loop, I increase m_move.totalTranslation value. The problem is that when m_move.totalTranslation equals 62, it doesn't enter if statement. It does, however, if it's larger than 62. Look at the log that was generated:

I0118 15:20:11.788576  5644 GameObject.cpp:270] totalTranslation: 61.008 tileSize: 62
I0118 15:20:11.806589  5644 GameObject.cpp:270] totalTranslation: 62 tileSize: 62
I0118 15:20:11.822602  5644 GameObject.cpp:270] totalTranslation: 62.93 tileSize: 62
I0118 15:20:11.822602  5644 GameObject.cpp:272] in!

As you can see, in! is only logged when totalTranslation is larger than 62. Why? I thought it might be casting problem, but I cast this tileSize which is of int type to double and still no difference.

هل كانت مفيدة؟

المحلول

For comparison of equality between floating point numbers, it is preferred to see the closeness of the numbers because of the internal representation of floating point numbers in the computer. You might have to check if the numbers are in epsilon distance of each other.The result of equality comparison depends on the particular compiler/machine.

Maybe you could look at this for more details: http://www.parashift.com/c++-faq/floating-point-arith.html

نصائح أخرى

Double sometime made annoying error... It seem to be 62.0, but in reality it's 61.9999999... but when you print it, it write you 62... Try this :

if (62.0 == totalTransaction + 0.01)
do something

When you are checking for equality of two doubles, you are on a right path to spefiy the epsilon, e.g. the acceptable margin.

double a = 62;
double b = 62.0000000000001;
double eps = 1e-10;

if (abs(a-b) < eps) {
    cout << "match!" << endl;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top