Friday 28 October 2016

c++ - Correct Way to Compare Floating-point Numbers

I'm calculating a real numeric value of the form N + fraction. Say, For example, N + fraction = 7.10987623, then N = 7 and fraction = 0.10987623 Next, I need to check to see if fraction is greater than or equal to the ratio 23269/25920.




The following, in C/C++, appears to give correct results; however, I'm not sure if it is the correct way to do the comparison:



// EPSILON is defined to be the error tolerance
// and `ratio' is defined as 23269.0/25920.0
if(fabs(fraction - ratio) > EPSILON)
// `fraction' is greater or equal to `ratio'


I also tried to do the other way, but it appears to give incorrect results.




if(fabs(fraction - ratio) < EPSILON)

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...