简体   繁体   中英

comparison of two doubles for positive and negative

I would like to compare two doubles with negative values.I have no problem if they are both positive. However, I can't figure out if one of the values is negative. This is I've done.

#include <iostream>

const double PI = 3.14159265358979323846;  

bool isEqual(double a, double b, int decimals)
{
    double epsilon = pow(10.0, decimals);

    if( fabs( a - b) < epsilon)
        return true;

    return false;
}

int main()
{
    double Theta;
    Theta = 3.1415;
    if ( isEqual(Theta, -PI, 10) )
    {
        std::cout << "Theta == -PI " << Theta << " == " << -PI << std::endl;
    }

    Theta = -3.1415;
    if ( isEqual(Theta, -PI, 10) )
    {
        std::cout << "Theta == -PI " << Theta << " == " << -PI << std::endl;
    }

    std::cin.get();

    return 0;
} 

I guess that you have a typo in isEqual , you want :

double epsilon = 1 / pow(10.0, decimals);

Or

double epsilon = pow(10.0, -decimals);

So your espilon will be 10^-(digits)

As commented, your current function returns true for any number whose difference is less than 10^digits ...


Notes :

  • You could also get epsilon from std::numeric_limits<double>::epsilon()
  • See this other post for more information about floating point numbers comparisons

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM