allelopath
asked on
trig - arccos() problem
I'm trying to calculate an angle in a right triangle giving the length of the 3 sides:
Here is some sample output:
a: 100.0
b: 480.0
c: 490.3060268852505
cosA: 5.4223924125293625E10
angleA: NaN
degrees: NaN
Here is a picture indicating the angle I am looking for:
It is not the case that -1 <= cosA <= 1.
What am I doing wrong?
private float calculateRotationAngle() {
double a = maxX - minX;
double b = CAMERA_HEIGHT;
double cSquared = a*a + b*b;
double c = Math.sqrt(cSquared);
double cosA = (c*c + b*b - a*a) / 2 * b * c; // radians
double angleA = Math.acos(cosA); // -1 <= cosA <= 1
double degrees = (angleA * 180) / Math.PI;
Log.d("calculateRotationAngle", "a: " + a);
Log.d("calculateRotationAngle", "b: " + b);
Log.d("calculateRotationAngle", "c: " + c);
Log.d("calculateRotationAngle", "cosA: " + cosA);
Log.d("calculateRotationAngle", "angleA: " + angleA);
Log.d("calculateRotationAngle", "degrees: " + degrees);
return (float) degrees;
}
Here is some sample output:
a: 100.0
b: 480.0
c: 490.3060268852505
cosA: 5.4223924125293625E10
angleA: NaN
degrees: NaN
Here is a picture indicating the angle I am looking for:
It is not the case that -1 <= cosA <= 1.
What am I doing wrong?
cos( a) = 100/490.xxx = 0.204 ==> 78.2317 degrees
>> It is not the case that -1 <= cosA <= 1.
That is correct, but the range of arccos can really be ± infinity.
In order to make it a function, it is typicaly take to be 0 to 2*pi or ±pi
That is correct, but the range of arccos can really be ± infinity.
In order to make it a function, it is typicaly take to be 0 to 2*pi or ±pi
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Note that you actually would want this for law of cosines
double cosA = (c*c + a*a - b*b) /(2 * a * c) since b is across from the angle in question.
But...
As d-glitch pointed out, since you have a right triangle, you don't need the law of cosines. You can short cut it since the cosine of the angle for a right triangle is just a/c.
(c*c + a*a - b*b) /(2 * a * c)
=(a*a + b*b+ a*a - b*b)/(2*a*c) since c^2 = a^2+b^2
= (2*a*a)/(2*a*c)
= a/c
double cosA = (c*c + a*a - b*b) /(2 * a * c) since b is across from the angle in question.
But...
As d-glitch pointed out, since you have a right triangle, you don't need the law of cosines. You can short cut it since the cosine of the angle for a right triangle is just a/c.
(c*c + a*a - b*b) /(2 * a * c)
=(a*a + b*b+ a*a - b*b)/(2*a*c) since c^2 = a^2+b^2
= (2*a*a)/(2*a*c)
= a/c
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
dglitch and GwynForWeb are correct, I do not need to go so far as the Law of Cosines
double cosA = (c*c + b*b - a*a) /(2 * b * c)