c++ - Why does floor of a whole number not equal itself (cpp)? -


i have double , int variable. product whole number. wanted check that, followed this method , puzzled ...

when this, acts it's supposed to:

#include <cmath>  double = 0.1; int b = 10; double product = * (double) b;  if(std::floor(product) == product){     // case true else{     // case false } 

but, strangely, doesn't work:

#include <cmath>  double = 0.1; int b = 10;  if(std::floor(a * (double) b) == (a * (double) b)){     // case false else{     // case true } 

can explain me?


edit:

to clarify, it's not just problem of fixed precision floating point calculation:

#include <cmath>  double = 0.1; int b = 10;  if((a * (double) b) == (a * (double) b)){     // case true else{     // case false } 

so product of a , b (although not precisely equal 1.0) of course equal itself, calling std::floor() messes things up.

this due rounding errors.

first of all, 0.1 can not stored in double exactly, product not 1.

secondly, and, think, more importantly in case, there more subtle reason. when compare results of computations directly instead of storing them double variables , comparing them (if (cos(x) == cos(y)) instead of a=cos(x); b=cos(y); if (a==b)...), may find operator== returning false even if x==y. reason explained here: https://isocpp.org/wiki/faq/newbie#floating-point-arith2 :

said way, intermediate calculations more precise (have more bits) when same values stored ram. <...> suppose code computes cos(x), truncates result , stores temporary variable, tmp. might compute cos(y), , (drum roll please) compare untruncated result of cos(y) tmp, is, truncated result of cos(x)

the same effect might take place multiplication, first code work, not second.


Comments