Reputation: 1299
So I have been given a project in which I have to write a Java program to return the angles between sides of a triangle given those three sides as parameters to a method. There is a mathematical formula that we can use to derive an equation we can use called the law of cosines, which is given sides of a triangle a, b, and c, c^2 = a^2 + b^2 - 2ab * cos(C) where C is some angle between sides a and b. We can isolate the angle C and we get the equation arccos((-c^2 + a^2 + b^2) / 2ab) = C. The math is simple enough, and it's easy to implement in Java, but when I input the sides 3, 4, 5, which should yield an output of 90, 30, 60, I get the angles 53.130102, 36.86989, 90.0. These are most definitely not the angles of a Pythagorean triple like 3, 4, 5. Does anyone know where I went wrong?
Code:
import static java.lang.Math.sqrt;
import static java.lang.Math.acos;
import static java.lang.Math.pow;
import static java.lang.Math.PI;
class Main {
public static void main(String[] args) {
anglesFinder(3, 4, 5);
}
public static void anglesFinder(int a, int b, int c) {
double alpha;
double beta;
double gamma;
alpha = (double) Math.acos((Math.pow(b, 2) + Math.pow(c, 2) - Math.pow(a, 2)) / (2 * c * b));
beta = (double) Math.acos((Math.pow(a, 2) + Math.pow(c, 2) - Math.pow(b, 2)) / (2 * a * c));
gamma = (double) Math.acos((Math.pow(a, 2) + Math.pow(b, 2) - Math.pow(c, 2)) / (2 * a * b));
System.out.println("angle between a & b is: " + (beta * (180 / Math.PI)));
System.out.println("angle between a & c is: " + (alpha * (180 / Math.PI)));
System.out.println("angle between b & c is: " + (gamma * (180 / Math.PI)));
}
}
Upvotes: 0
Views: 175
Reputation: 178283
Your program is correct but you are incorrect. Angles of 30, 60, and 90 degrees would be expected for a right triangle of sides of (proportional) length 1, sqrt(3)/2 (about 0.866), and 2, which doesn't scale to lengths 3, 4, and 5.
My calculator gives about 0.6 for the cosine of 53.130102 degrees, and about 0.8 for the cosine of 36.86989 degrees, which matches lengths 3, 4, and 5.
Upvotes: 3