Mamen - 1 year ago 54

C Question

i make a simple program to prove a right triange , then i'm using

`pow`

`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`

`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

Answer Source

`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.