A way to compare floating point values


if(0.3==0.2) ...

You shouldn't do that of course. But there is a nice workaround if you are satisfied with the numbers being within some defined epsilon proximity. A way to do this is to get the difference between them and compare it to some chosen epsilon. If it is less, declare them equal.


if(std::fabs(0.3-0.2)<1e-10) ...

But this looks nothing like comparing for equality. Also, good luck changing that epsilon consistently in a couple of years. Instinctive reaction when making something more managable is to make a function out of it.


bool equals(double v1, double v2, double eps=1e-10) { 
   return std::fabs(v1-v2)<eps; 
}
...
if(equals(0.3, 0.2, 1e-10)) ...

Better, but try reading it aloud. It's how a robot from 60's science fiction would speak. And which number is epsilon? (I take that back. It's obvious in this case, but I insist it will not always be.)

Consider instead the following draft of a class:


class dbl
{
private:
   double m_val;
public:
   explicit dbl(double val) : m_val(val) {};
   dbl equals(double val) {
      return dbl(m_val-val);
   }
   bool within_epsilon(double eps = 1e-10) {
      return std::fabs(m_val) <= eps;
   }
};
...
if(dbl(0.3).equals(0.2).within_epsilon(1e-10)) ...

Yes, it's a builder pattern for building the simplest of all data types, but the meaning couldn't be clearer and it reads like a poem! But ... performance, you say. I measured. With my setup, they all equally take just over 100 CPU cycles.


Previous: Using smart pointers in building trees in which child nodes need an access to the parent
Next: An ulta-paranoid tinfoil hat implementation of reasonably safe storage for numerical types