2

So, I have two double variables, and I want to compare them till 3 decimal places. So, for variables (for example):

double x = 0.695999;
double y = 0.695111;

if I check for (x==y), it should return true (since both are equal till 3 decimal places). Thanks!

Darth.Vader
  • 5,079
  • 7
  • 50
  • 90
  • How does the compiler and even us know that is your intention? The compiler/us are not physic – Ed Heal Mar 03 '13 at 07:55
  • may be, if C has a function like: compare(double v1, double v2, int precision)? Not a psych, but we passing the information to the method parameters? – Darth.Vader Mar 03 '13 at 07:56

2 Answers2

7

You can (ab)use integer comparison and truncation:

int is_equal_3decplaces(double a, double b) {
    long long ai = a * 1000;
    long long bi = b * 1000;
    return ai == bi;
}

As @DavidRF's benchmarks have shown it, this solution offers a slight (~40%) improvement in performance compared to calculating the absolute values.

4

You should actually check for the difference being less than a small delta which is pre-configurable, unless you always want it to be checked for three decimal places. For example:

#define epsilon ((double)0.000999)
bool is_approximately_equal(double x, double y)
{
        return (abs(x - y) < epsilon);
}

Note that abs on C++ has the version of abs for double. In C you'll have to do something with -ve values.

mttrb
  • 8,297
  • 3
  • 35
  • 57
user1952500
  • 6,611
  • 3
  • 24
  • 37
  • 1
    Changed. Thanks! Thought the other was more instructive but anyways doesn't change much. – user1952500 Mar 03 '13 at 08:01
  • @mttrb, right. I mixed c++ and c (std::cmath has the double and float versions). Added a comment on that. – user1952500 Mar 03 '13 at 08:02
  • I am actually using arduino - I am not sure if it is based on C or C++ and if abs will work for me on arduino... if it doesn't I will just write my own abs() function. – Darth.Vader Mar 03 '13 at 08:07
  • It looks like `abs` is defined as `#define abs(x) ((x)>0?(x):-(x))` in `Arduino.h` so it should work on the doubles and integers. – mttrb Mar 03 '13 at 08:37