2

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;
} 
CroCo
  • 5,531
  • 9
  • 56
  • 88
  • 4
    I think you probably want `pow(10.0, -decimals)` in your `isEqual` definition. – Mark Dickinson Jul 30 '14 at 20:34
  • 7
    `epsilon = pow(10.0, decimals);` with `decimals == 10`. So according to your function, every pair of numbers whose difference is less than `10000000000` are equal :) – T.C. Jul 30 '14 at 20:35
  • 1
    Please clarify. What is your actual question? As stated, with `decimals = 10`, neither of those tests will pass and you will see nothing printed. Is this what you want? If not, what *do* you want to see? – Jashaszun Jul 30 '14 at 20:49
  • Do you want both calls to `isEqual()` to return `TRUE` in `main()`? or only the second call should return true? – DaveS Jul 30 '14 at 21:06
  • @MarkDickinson, thanks it did the trick. I accept it as a first answer, however since it is a comment, I will consider another answer for the sake of closing this post as a solved problem. – CroCo Jul 30 '14 at 21:10

1 Answers1

3

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
Community
  • 1
  • 1
quantdev
  • 23,517
  • 5
  • 55
  • 88