当前位置:   article > 正文

float浮点数相比较会导致的错误!(浮点数精度导致的坑!!!)_float t = 0.f

float t = 0.f

以前从来没有在意浮点数精度会导致错误,但现在自己遇到了~~

如果有两个浮点数a , b,用a == b去作为某个判断条件,那么大概率会出现bug,并且如果也像我一样,对精度问题不在意,可能摸不着头脑!

所以,建议用fabs(a-b) < 1e-6的方式,去判断两个浮点数是否相等,而这个1e-6就是项目要求的精度啦,可以随情况修改

以下做两组实验验证这一结论

1.两个浮点数直接比较

        float t = 0.0f,T = 0.005f;
		
	   //让t随着i增长而累加T,然后判断t与i*T是否相等
	   
        for(auto i = 0;i < 20;i++){
            std::cout << "t:" << t << "   i*T:" << i*T << "   is equal:" <<  (t == i*T)  <<std::endl;
            t += T;
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
运行结果
// is equal 中,1代表系统判断相等,0代表系统判断不相等
t:0   i*T:0   is equal:1
t:0.005   i*T:0.005   is equal:1
t:0.01   i*T:0.01   is equal:1
t:0.015   i*T:0.015   is equal:1
t:0.02   i*T:0.02   is equal:1
t:0.025   i*T:0.025   is equal:1
t:0.03   i*T:0.03   is equal:0
t:0.035   i*T:0.035   is equal:0
t:0.04   i*T:0.04   is equal:0
t:0.045   i*T:0.045   is equal:0
t:0.05   i*T:0.05   is equal:0
t:0.055   i*T:0.055   is equal:0
t:0.06   i*T:0.06   is equal:0
t:0.065   i*T:0.065   is equal:0
t:0.07   i*T:0.07   is equal:0
t:0.075   i*T:0.075   is equal:1
t:0.08   i*T:0.08   is equal:1
t:0.085   i*T:0.085   is equal:1
t:0.09   i*T:0.09   is equal:0
t:0.095   i*T:0.095   is equal:0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

由此可见,直接让系统判断两个浮点数是否相等的方式非常不靠谱~~

2.利用fabs()比较

        float t = 0.0f,T = 0.005f;
		
	   //让t随着i增长而累加T,然后判断t与i*T是否相等
        for(auto i = 0;i < 20;i++){
            std::cout << "t:" << t << "   i*T:" << i*T << "   is equal:" << (fabs(t -i*T) < 1e-6)  <<std::endl;
            t += T;
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
运行结果
// is equal 中,1代表系统判断相等,0代表系统判断不相等
t:0   i*T:0   is equal:1
t:0.005   i*T:0.005   is equal:1
t:0.01   i*T:0.01   is equal:1
t:0.015   i*T:0.015   is equal:1
t:0.02   i*T:0.02   is equal:1
t:0.025   i*T:0.025   is equal:1
t:0.03   i*T:0.03   is equal:1
t:0.035   i*T:0.035   is equal:1
t:0.04   i*T:0.04   is equal:1
t:0.045   i*T:0.045   is equal:1
t:0.05   i*T:0.05   is equal:1
t:0.055   i*T:0.055   is equal:1
t:0.06   i*T:0.06   is equal:1
t:0.065   i*T:0.065   is equal:1
t:0.07   i*T:0.07   is equal:1
t:0.075   i*T:0.075   is equal:1
t:0.08   i*T:0.08   is equal:1
t:0.085   i*T:0.085   is equal:1
t:0.09   i*T:0.09   is equal:1
t:0.095   i*T:0.095   is equal:1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

利用这种方式去判断,就可以得到令人放心的结果!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/108516
推荐阅读
相关标签
  

闽ICP备14008679号