Link to home
Start Free TrialLog in
Avatar of allelopath
allelopath

asked on

trig - arccos() problem

I'm trying to calculate an angle in a right triangle giving the length of the 3 sides:
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;
		
}

Open in new window


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:
User generated image
It is not the case that  -1 <= cosA <= 1.
 What am I doing wrong?
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

It is an order of operations issue. Change line 8 to this:

double cosA = (c*c + b*b - a*a) /(2 * b * c)
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
SOLUTION
Avatar of d-glitch
d-glitch
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of allelopath
allelopath

ASKER

dglitch and GwynForWeb are correct, I do not need to go so far as the Law of Cosines