cepsilon

How to set mathematical precision in equations?


How do I set mathematical precision for the following code?

int calc(double a, double b)

  if(a == b){
    printf("= ");
  }else if(a < b){
    printf("< ");
  }else{
    printf("> ");
}
 }

Where a and b can be either of these:

double tr = p1 + p2 + p3;
double ob = (p1 + p2) * 2;
double sq = p1 * 4;
double s = (p1 + p2 + p3)/2;
double trS = sqrt(s * (s - p1) * (s - p2) * (s - p3));

The problem that I have right now is that although a == b if calculated on a calculator in decimal system, but not here. It will skip the first if-statement and print that a is either bigger or smaller than b.

I have read quite a few similar questions on SO, but none of them worked for me. I've tried:

if(fabs(a-b) <= DBL_EPSILON)

Can someone please tell what did I miss? Thanks :)


Solution

  • Floating point operations are by their nature inexact.

    If you have to use floating point, you need to decide how close is "close enough" for your purposes. For example, you could check to see if the two values are within 0.001 of each other if that's the level of precision you care about.