/* I am a point in two space. I am represented in cartesian coordinates, but I can answer my polar coordinates. I am immutable. */ public class TwoDPoint { /* Create a point in cartesian (x,y) or polar (r,theta) coordinates, depending on the specified type. Angles are specified in radians. */ public TwoDPoint (double arg1, double arg2, int type) { if (type == CARTESIAN) { x = arg1; y = arg2; } else if (type == POLAR) { x = arg1 * Math.cos (arg2); y = arg1 * Math.sin (arg2); } else throw new Error ("unknown point type"); } /* Cartesian accessors. */ public double getX () {return x;} public double getY () {return y;} /* Polar radius accessor. */ public double getR () { return Math.sqrt (x * x + y * y); } /* Polar angle accessor. Answer the angle the receiver makes with origin in radians. Result will be between 0 and 2*pi radians. Right is 0. Up or down, depending on your coordinate system, is pi/2 (90 degrees). When using the standard trig coordinate system, angles increase counter-clockwise from right. When using the standard computer coordinate system, angles increase clockwise from right. */ public double getTheta () { if (x == 0) { if (y >= 0) return Math.PI * 0.5; else return Math.PI * 1.5; } double result = Math.atan (y / x); if (x < 0) result += Math.PI; else { if (result < 0) result += Math.PI * 2; } return result; } /* Euclidean distance metric. */ public double distanceTo (TwoDPoint p) { double dx = getX () - p.getX (); double dy = getY () - p.getY (); return Math.sqrt (dx * dx + dy * dy); } /* Vector angle between two points. */ public double angleTo (TwoDPoint p) { double dx = getX () - p.getX (); double dy = getY () - p.getY (); TwoDPoint delta = new TwoDPoint (dx, dy, CARTESIAN); return delta.getTheta (); } private double x; private double y; public final static int CARTESIAN = 0; public final static int POLAR = 1; }