Reputation: 103
I'm doing a project for my school, where I have to create a method that calculates the angle of a triangle. We're using the law of cosines, but I'm afraid I don't understand it at all. I know there's a formula I can use, but I've entered in the values in wolfram alpha, but they're completely different (when I take out the Math.acos part) or just don't return a number at all (with Math.acos). I've tried a ton of different things (including just taking out the Math.acos part to see what happens, I get something like 1 or 3), but here's what I have so far:
public static double angle(double a, double b, double c) {
return Math.acos((Math.pow(a, 2) + Math.pow(b, 2) + Math.pow(c, 2)) / (2 * b * c));
}
The parameters stand for the lengths of each side. I keep receiving the result "NaN". I know the method Math.acos will return that if the number is receives is over one, but it's hard to work this out when I don't understand what I'm working with at all. Any help at all is appreciated, thank you!
Upvotes: 1
Views: 5598
Reputation: 1691
Your code have some mistake, the correct formula is cos(y) = (a^2 + b^2 - c^2) / 2ab
, I fixed below:
public static double angle(double a, double b, double c) {
return Math.acos((Math.pow(a, 2) + Math.pow(b, 2) - Math.pow(c, 2)) / (2 * a * b));
}
public static void main(String[] args) {
System.out.println(angle(10, 10, 10));
System.out.println(Math.toDegrees(angle(10, 10, 10)));
}
Result is:
run:
1.0471975511965979
60.00000000000001
BUILD SUCCESSFUL (total time: 0 seconds)
Hope this help.
Upvotes: 5