开发者

fine tuning the == operator to match double percision

In my code there is a parameter I am calculating. During many of the test runs, this parameter should be 0. Since the parameter is calculating through multiple additions and subtractions, it is not exactly 0 but it is less than 10^-10. Currently I am using:

double tol = pow(10,-10);
if (fabs(delta_U) < tol)){//whatever
}

Is there a more elegant way to do 开发者_StackOverflowso?


It looks fine. You could just write the tolerance directly, instead of computing it with pow.

double tol = 1e-10;


jpalecek is correct - saves computation of a constant.

I do not know the nature of the calculations but you could either possibly

  • Reduce the errors by modifying the order of calculations and operators
  • Possibly make the calculation use integers


Wrap it in a function so it is more clear what you are trying to do:

if (near_zero(delta_U))
{
   // ...
}

where:

inline bool near_zero(double d)
{
   return fabs(d) < 1e-10;
}


You can specify floating point in scientific notation:

if (fabs(delta_U) < 1e-10)
{
   //whatever
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜