How to deal with excess precision in floating-point computations?

前端 未结 5 1238
悲&欢浪女
悲&欢浪女 2020-12-10 15:28

In my numerical simulation I have code similar to the following snippet

double x;
do {
  x = /* some computation */;
} while (x <= 0.0);
/* some algorithm         


        
5条回答
  •  借酒劲吻你
    2020-12-10 15:52

    In your question, you stated that using volatile will work but that there'll be a huge performance hit. What about using the volatile variable only during the comparison, allowing x to be held in a register?

    double x; /* might have excess precision */
    volatile double x_dbl; /* guaranteed to be double precision */
    do {
      x = /* some computation */;
      x_dbl = x;
    } while (x_dbl <= 0.0);
    

    You should also check if you can speed up the comparison with the smallest subnormal value by using long double explicitly and cache this value, ie

    const long double dbl_denorm_min = static_cast(std::numeric_limits::denorm_min());
    

    and then compare

    x < dbl_denorm_min
    

    I'd assume that a decent compiler would do this automatically, but one never knows...

提交回复
热议问题