赞
踩
以前从来没有在意浮点数精度会导致错误,但现在自己遇到了~~
如果有两个浮点数a , b,用a == b去作为某个判断条件,那么大概率会出现bug,并且如果也像我一样,对精度问题不在意,可能摸不着头脑!
所以,建议用fabs(a-b) < 1e-6的方式,去判断两个浮点数是否相等,而这个1e-6就是项目要求的精度啦,可以随情况修改
以下做两组实验验证这一结论
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;
}
// 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
由此可见,直接让系统判断两个浮点数是否相等的方式非常不靠谱~~
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;
}
// 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
利用这种方式去判断,就可以得到令人放心的结果!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。