Comparision of double values

0

Hi,
I am doing double value comparision check as shown in below code

double m_Initial = 5.0;
double m_final = 5.1;
if(((m_final) - (m_Initial + 0.1)) > 0) 
{
// True
}
else
{
// false
}

It is going to "True" case always. And also, I tried comparison below code using: "EPSILON" / "DBL_EPSILON"
double m_Initial = 5.0;
double m_final = 5.1;
if(((m_final) - (m_Initial + 0.1)) > EPSILON) 
{
// True
}
else
{
// false
}

Please suggest common solution, for doing comparison of double values.

Responses (2)
  • Accepted Answer

    Thursday, January 11 2018, 03:22 AM - #Permalink
    0

    Hi,

    - for me this version works correctly.

    bool    r;

    void __fastcall TForm3::Button1Click(TObject *Sender)

    {

    double m_Initial = 5.0;

    double m_final = 5.1;

     

    if(((m_final) - (m_Initial + 0.1)) > 0.0) // 0.0 isn't integer

    {

     r=True;

    }

    else

    {

     r=false;

    }

    }

    Thanks.

     

    The reply is currently minimized Show
  • Accepted Answer

    Thursday, January 11 2018, 01:44 AM - #Permalink
    0

    Hi Ajay,

    This is simply the pitfalls of using floating point numbers on a computer.

     m_Initial + 0.1 will only be very close but not necessarily equal to m_final

    If you want to check if m_initial + 0.1 is equal to m_final one way to do it is as follows:

    #include      // includes definition of the fabs function (calculate absolute value (ie remove sign)).

    const double SmallValueThatIsConsideredToBeCloseEnoughForYourApplication = 0.0001;

    if (fabs((m_final) - (m_Initial + 0.1)) > SmallValueThatIsConsideredToBeCloseEnoughForYourApplication ) {

       // here if not equal

       }

    else {

       // here if equal

    }

    // Regards, roger

     

    The reply is currently minimized Show
Your Reply

Please login to post a reply.........