Mamen
Mamen

Reputation: 1446

compare 2 values in c always return false

i make a simple program to prove a right triange , then i'm using powfunction to multiple the input like ;

if(pow(c,2) == (pow(a,2) + pow(b,2))){
   printf("True.");
}else{
   printf("False.");
}

then i entered the value to a = 3, b = 4, c = 5 , it should be true because 25 == 25 but it returned a false,

but if i change the code to this :

if((c*c) == ((a*a) + (b*b))){
   printf("True.");
}else{
   printf("False.");
}

the result is true

nb : input is a double

any explanation of this error ? thank you

Upvotes: 2

Views: 164

Answers (1)

Bathsheba
Bathsheba

Reputation: 234885

pow(x, y) is normally implemented as exp(y log x). This can go off for even seemingly trivial values of the arguments.

You are seeing the effect of this.

There's no hard and fast rule for dealing with floating point precision issues. Comparing with a tolerance is often mooted as a solution but picking the level of tolerance or the way it ought to be applied is not in itself trivial.

In your case it would be best to compare a * a + b * b with c * c; particularly if these are always integral values.

Upvotes: 6

Related Questions