Can any one give me an idea for compare these two values in double data type.

I hope this if check always gets FALSE, Unfortunately It is TRUE condition. IF you know any solution,Plz suggest to me.

# include <stdio.h>

int main()
{
    double g =  51.200000000000007;
    double h =  51.200000000000001;

    if((g)>(h))
    {
        printf("%lf",h);
    }
    g=g;
    h=h;

    printf("%lf",g);

    return 0;
}

Output:
51.200000
51.200000

Recommended Answers

All 6 Replies

Double variables just don't have that much precision. If you need numbers that are that fine-tuned, you need to look for an "arbitrary/multiple precision" library - something like GMP http://gmplib.org/

Hope this helps.

Thanks to your support.

I need Clarity of answer like only 51.2 ..

Input : 51.2 i was given , But compiler take it as a 51.200000006.
For the next time, 51.200000001

After comparing these values its not equal . But it should be equal ...

Hope everyone understand my problem,

Actually i want to skip that much of accuracy.

Made this in a hurry, but it should work. Requires the math header. Basically you take the numbers you want to compare, multiply them by 10 to the power of your precision, trim them by casting to int, do your comparison, and your done.

inline int CompareDoubles(double A, double B, int Precision) {

  int a = (int)(A * pow(10, Precision));
  int b = (int)(B * pow(10, Precision));

  if (a > b) 
    return 1;
  else if (a == b)
    return 0;
  else
    return -1;
}

So using your example, here is the usage.

int main()
{
  double g = 51.200000000000007;
  double h = 51.200000000000001;

  if(CompareDoubles(g,h,1) > 0) // This will only compare "51.2", ignoring the rest
    printf("%lf",h);

  g=g;
  h=h;

  printf("%lf",g);

  return 0;
}

Thanks NIGHTS, But my problem is like below two values should matches ....
Is there any header files wants to include. like float.h ..

i m working with gcc compiler , eclipse c editor,, Is it necessary to move other compiler...

double g =  9.5999999999999;
	double h =  9.6000000000001;

Oops, your right. Sorry about that. Here you go...

inline int CompareDoubles(double A, double B, int Precision) {

  int a = (int)round(A * pow(10, Precision));
  int b = (int)round(B * pow(10, Precision));

  if (a > b) 
    return 1;
  else if (a == b)
    return 0;
  else
    return -1;
}

So now, before truncating the end digits, it will round the numbers to the nearest given precision. That should work, right?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.