This question already has answers here:
Floating point equality and tolerances
                                
                                    (7个答案)
                                
                        
                        
                            How dangerous is it to compare floating point values?
                                
                                    (10个回答)
                                
                        
                                5年前关闭。
            
                    
我正在计算形式为N + fraction的实数值。说,例如N + fraction = 7.10987623,然后N = 7fraction = 0.10987623接下来,我需要检查fraction是否大于或等于比率23269/25920

在C / C ++中,以下内容似乎可以给出正确的结果;但是,我不确定这是否是进行比较的正确方法:

// 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'


我还尝试了另一种方法,但似乎给出了错误的结果。

if(fabs(fraction - ratio) < EPSILON)

最佳答案

您有比较平等的正确方法:

fabs(fraction - ratio) < EPSILON


这将在width ratioEPSILON周围建立一个相等带。超出该范围的任何范围都严格大于。因此,>检查为:

fraction > ratio + EPSILON


既然我们想要>=,我们只需将这两部分结合起来即可:

fraction > ratio - EPSILON

09-10 01:26
查看更多