Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a triangle is a right triangle

Tags:

java

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!

like image 485
Frankmeister Avatar asked Dec 19 '14 05:12

Frankmeister


2 Answers

I see a number of problems:

  • you check both a2 + b2 = c2 and b2 + a2 = c2, but these are actually equivalent
  • you never check if a2 + c2 = b2.
  • you use Math.pow to square a number, which is both inefficient and imprecise. (You should just use *.)
  • you expect floating-point arithmetic to give an exact value — suitable for == — which it generally does not.
like image 139
ruakh Avatar answered Sep 22 '22 23:09

ruakh


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.

like image 22
Chris Jester-Young Avatar answered Sep 26 '22 23:09

Chris Jester-Young