I'm trying to check to see if a triangle is a right triangle in Java. This is a portion of what the tester class does:
Triangle a = new Triangle(new Point(2, 2), new Point(6, 2), new Point(2, 6) );
System.out.println(a.isRight()); //Expects True
A portion of my triangle class receives the values and sets them to x1,y2 etc:
public Triangle(Point loc1, Point loc2, Point loc3) {
x1 = loc1.getX(); y1 = loc1.getY();
. . .
The first two segments of code were given to me. I am to make the last segment of code which I made to be this:
public boolean isRight() {
if((Math.pow(side1,2)+Math.pow(side2,2)) == Math.pow(side3,2))
return true;
if((Math.pow(side2,2)+Math.pow(side1,2)) == Math.pow(side3,2))
return true;
if((Math.pow(side3,2)+Math.pow(side2,2)) == Math.pow(side1,2))
return true;
else
return false;
}
However, it still returns false. What am I doing wrong? Thanks a bunch!
Update: Thanks for the help. I seem to have made a rather noob-ish mistake. I never thought about the fact that doubles weren't really accurate (sorry, just trying to say what I did in simple terms). I ended up inputting this:
if(Math.abs(side1*side1 + side2*side2 - side3*side3) < 0.2)
return true;
if(Math.abs(side1*side1 + side3*side3 - side2*side2) < 0.2)
return true;
if(Math.abs(side3*side3 + side2*side2 - side1*side1) < 0.2)
return true;
else
return false;
Once again, thanks for the help!
I see a number of problems:
Math.pow
to square a number, which is both inefficient and imprecise. (You should just use *
.)==
— which it generally does not.Floating-point numbers are not exact, and comparisons using ==
will often fail. You should instead take the absolute difference between the two numbers and make sure it's very small:
private static boolean closeEnough(double a, double b) {
return Math.abs(a - b) < 0x1p-32;
}
You can use a different threshold from 0x1p-32
if you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With