- I've been making this code to determine if a triangle can be a right triangle without using sqrt() or abs() by taking three sides and figuring out if the absolute difference between them is less than Epsilon, or 0.05. But it only works in some cases. What am I doing wrong?
int IsRightTriangle(float side1, float side2, float side3)
{
if (side3*side3-(side1*side1+side2*side2) <= 0.05 || side3*side3-(side1*side1+side2*side2) >= -0.05) {
return 1;
}
else if (side1*side1-(side3*side3+side2*side2) <= 0.05 || side1*side1-(side3*side3+side2*side2) >= -0.05) {
return 1;
}
else if (side2*side2-(side3*side3+side1*side1) <= 0.05 || side2*side2-(side3*side3+side1*side1) >= -0.05) {
return 1;
}
else
return 0;
}
I have tried multiple iterations of this code, and they all got results similar to this:
Running test: IsRightTriangle(edge1=15.00, edge2=27.00, edge3=29.55) -- Passed
Running test: IsRightTriangle(edge1=21.02, edge2=19.00, edge3=9.00) -- Failed
I'd expect
&&
instead of||
as the compare needs to meet both conditions to be a "right" triangle.Think of
as
d <= 0.05 || d >= -0.05
is always true (unless sides had a not-a-number).Certain it should use
d <= 0.05 && d >= -0.05
.Other issues exist too.
Suggested alternative algorithm:
Determine the the side with the largest magnitude squared - the candidate hypotenuse squared. This negates the need for square root and absolute value.
Sum the other 2 squares.
Relatively compare the two for nearness to 1.0 (a right triangle).
Code is dealing with floating point values.
IsRightTriangle(15.00 , 27.00 , 29.55)
should get the same result asIsRightTriangle(15.00e10 , 27.00e10 , 29.55e10)
and asIsRightTriangle(15.00e-10, 27.00e-10, 29.55e-10)
.Example: Lightly tested sample code:
Notes:
double
orfloat
? OP is usingfloat
arguments, yetdouble
constants and discussesdouble
functions likesqrt()
instead ofsqrtf()
.abs()
is an integer function and has no place here. Instead discussfabs()
,fabsf()
.