0

I wrote a small test to evaluate my programm, but somehow a weired thing happens:

Values of the vector(as printed using 'cout' in the first loop): 0.06 0.06 0.06 0.06 0.06 0.6

Message triggered by the call of function fail

Adjustment at i=4 was 0.06, but should have been 0.06

Somehow this fairly easy comparison of two floats returns false in this loop, but numbers are equal printed and should be equal. Furthermore from i=0 to i=3 comparison of the values evaluate as they should (returning equal)

Somebody know what the problem is?

vector<float> adjustment = *adj.getCalculatedAdjustment();
for (vector<float>::iterator it = adjustment.begin();it!=adjustment.end();it++){
    cout << *it << "\n";
}
for (unsigned int i=0;i<adjustment.size()-1;i++){
    if (adjustment[i]!=(float)0.06){
        stringstream ss;
        ss << "Adjustment at i=" << i << " was " << adjustment[i] << ", but should have been 0.06";
        fail(ss.str());
    }

}
malger
  • 173
  • 1
  • 2
  • 7
  • "fairly easy comparison of two floats". Comparing two floats is not exactly easy. You should try to learn more about it. – JBL Dec 08 '14 at 14:02
  • can you write how you fill the vector. – Adem Dec 08 '14 at 14:03
  • This might help https://randomascii.wordpress.com/2012/02/11/they-sure-look-equal/ – Richard Critten Dec 08 '14 at 14:04
  • http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples – Ken White Dec 08 '14 at 14:05
  • Thanks for your answers. I did know about the problematic of comparing float values, but I did not know, that 'cout' would not be accurate and round these float values... – malger Dec 08 '14 at 14:25

0 Answers0