Thursday, 6 October 2016

C++ Floating point gotcha











I am new to C++. I had a doubt, while reading C++.
How to decide two floating point numbers equal to each other or not ?



Thanks in advance


Answer



Obviously, you should not use operator == to compare them.




The important concept here is if the difference of your two floating point number is small enough to the precision requirement of your problem to solve or smaller than your error range, we should consider them as equal.



There are some practical methods suggestions such as



  fabs(f1 - f2) < precision-requirement
fabs(f1 - f2) < max(fabs(f1), fabs(f2)) * percentage-precision-requirement

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...