0

I have the following section in my program:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main ()
{
   double a, b, c, check;
   check = (pow(a,2) + pow(b,2) + pow(c,2));

   if (check !=1 )
   {
        printf("a^2+b^+c^2 = %f, and is not equal to 1\n", check);
        printf("do something\n");
   }
   else
   {
        //conginue with something
   }
}

When I run the program, the if else condition fails even when the value of check is 1.

I get the following message:

The value of a^2+b^2+c^2 is 1.000000 and is not equal to 1.

I tried to do it with

if (check !=1.000000 )

and still the result is same.

Can any one help me with this?

JohnP
  • 109
  • 1
  • 10

1 Answers1

3

I assume the values of a,b,c are decimals with several digits. For example: if all a, b, c are 0.577350269189626 the result is "almost" 1.00000

But there may be a small difference, for example it can be 1.0000000000001

Comparing double precision numbers against exact values is not safe. It maybe better to have some kind of precision value, like:

double precision = 0.00001;

Then you can perform a safe comparison:

if (abs(check - 1.0000) > precision)
{
    // not equal to 1 at all
}
else 
{
    // almost equal to 1
} 
Jaime
  • 5,770
  • 4
  • 23
  • 50