Granny's Programming Pearls "inside of every large program is a small program struggling to get out" JavaRanch.com/granny.jsp
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# How to calculate the angle of 2 points on a circle in clockwise direction

mark baum
Greenhorn
Posts: 18
Hi,

I'm trying to calculate the angle of 2 points anywhere on a circle in a clockwise or anticlockwise direction, so the angle can vary from 0 to 360 degrees, the center of the circle being 0,0.

I tried various methods, asin, atan like

double angle_Entry = Math.atan(y_1_km/x_1_km);
double angle_Current = Math.atan(y_2_km/x_2_km);
return angle_Current - angle_Entry;

and eventually also a vector based approach like this:

x1*x2 + y1*y2 (assuming that since both point have the same distance (radius), it's a unit vector and it's not necessary to divide through the radius)

All methods work fine until 180 degrees, but the test for 270 degrees always fail:

x_1_km = 0;
y_1_km = 100;
x_2_km = -100;
y_2_km = 0;

assertEquals(2*Math.PI*3/4, circleTrack.getAngleOf2PointsOnCircle(x_currentPosition_km, y_currentPosition_km, x_CircleEntrance_km, y_CircleEntrance_km), 0.0000000000001);

All attempts return 90 degrees instead of 270 (rsp 2*Math.PI*3/4). I saw the influence of the opposite sign, but my math skills seem to to be too long out of use to find how to solve the issue in a elegant way.

I was thinking that I could might write an algorithm defining the line on the diameter and use it to detect if the second point is on the same (first) half as first point or on the second half, that would resolve the issue. but I thought there must be an existing and maybe better solution for this.

Thanks for any help

Marc

Ankit Garg
Sheriff
Posts: 9610
37
Well I'm not a math guy, but did you try a google search like this??

Ankit Garg
Sheriff
Posts: 9610
37

Piet Verdriet
Ranch Hand
Posts: 266
You'll probably want to do something like this:

Disclaimer: didn't properly test this!

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?