Complex Angles, you don't need trig

So I offered some of my code and was called on it. Turns out my core code is now all 3d with Quaternions etc. However 2d is even easier to avoid trig and even inverse trig. Done right you don’t need all that many sqrts, but even then they are pretty fast.

The idea is simple. A complex number simply represents a unit vector in the direction the angle represents. Turns out complex multiplication is the same as adding angles and complex division is the same as subtracting angles. Since if we start with normalized values we end up with normalized values. Sure there is a little error. You can see that with the java2d demo that is included. You can even compare angles to see which is larger or smaller. Like atan2 angles are implied to be signed ±PI.

In the example the sweeping line is red when smaller than angle to the mouse and blue when larger. It turns green when its in the “acceptance cone”, in this case ±8deg. Finally the funny cyan lines demonstrate interpolation.

Sorry i can’t work out how to put this in a scroll box.

This code has not been unit tested. Use any way you want. I take no responsibility for this code, use at your own risk. And its in the public domain.


import static java.lang.Math.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
 * other code has too much noise. This is suppose to be clean and make it easy for the jgo use. I use a demo java2d example. We use the convention that x is the
 * real axis and y is the imaginary axis.
 * 
 * Note that i assume things are normalized a lot. Since this always represents an angle then this should always have unit length.
 * 
 * Numerical errors for doubles are rather low. But they will eventrually accumulate. But its not like you need to normalize after every operation. 
 * 
 * Some degen cases are not checked. In particular you can create a NaN,NaN angle if you create an angle with 0,0. 
 * 
 * @author bob
 * 
 */
public class ComplexAngle implements Comparable<ComplexAngle> {
	/**
	 * Warning these are mutatable. 
	 */
	public static final ComplexAngle DELTA_ANGLE = createAngle(PI * 2 / 720);//1/2 def
	public static final ComplexAngle RIGHT_ANGLE=createAngle(PI/2);
																												
	private double real = 1;
	private double imag = 0;

	private ComplexAngle(double r, double i) {
		real = r;
		imag = i;
	}

	public static ComplexAngle angleTo(Point2D from, Point2D to) {
		return createAngle(to.getX() - from.getX(), to.getY() - from.getY());
	}

	public static ComplexAngle createAngle(double x, double y) {
		ComplexAngle ca = new ComplexAngle(x, y);
		ca.normalize();
		return ca;
	}
	
	public static ComplexAngle createAngle(double rad) {
		ComplexAngle ca = new ComplexAngle(Math.cos(rad), Math.sin(rad));
		
		return ca;
	}

	public ComplexAngle addAngleThis(ComplexAngle c) {
		return multiplyThis(c);
	}

	public ComplexAngle addAngle(ComplexAngle c) {
		return multiply(c);
	}

	/**
	 * adds angles.
	 * 
	 * @param c
	 */
	public ComplexAngle multiplyThis(ComplexAngle c) {
		double nr = real * c.real - imag * c.imag;
		double ni = real * c.imag + imag * c.real;
		real = nr;
		imag = ni;
		// Normalized since both should be length 1. This adds the angles.
		return this;
	}

	public ComplexAngle multiply(ComplexAngle c) {
		double nr = real * c.real - imag * c.imag;
		double ni = real * c.imag + imag * c.real;
		return new ComplexAngle(nr, ni);
	}

	public ComplexAngle subtractAngleThis(ComplexAngle c) {
		return divideThis(c);
	}

	public ComplexAngle subtractAngle(ComplexAngle c) {
		return divide(c);
	}

	/**
	 * subtracts angles.
	 * 
	 * @param c
	 */
	public ComplexAngle divideThis(ComplexAngle c) {
		double nr = real * c.real + imag * c.imag;
		double ni = c.real * imag - c.imag * real;
		// since we assume normalized we don't need to divide by
		// c.real*c.real+c.imag*c.imag, since that is 1.
		real = nr;
		imag = ni;
		return this;
	}

	public ComplexAngle divide(ComplexAngle c) {
		double nr = real * c.real + imag * c.imag;
		double ni = c.real * imag - c.imag * real;
		return new ComplexAngle(nr, ni);
	}

	/**
	 * compare the angle. If o is bigger that means its a bigger angle. Note this is signed angles.
	 * 
	 * So we are comparing y/x >=<  y'/x'. To avoid degenrancy with x->0 we rearange for y*x' >=< y'*x
	 */
	@Override
	public int compareTo(ComplexAngle o) {
		double a = imag*o.real;
		double b = o.imag*real;
		if (a > b)
			return 1;
		if (a < b)
			return -1;
		return 0;
	}

	/**
	 * note that we are using signed angles +-PI
	 * 
	 * @param coneHalfAngle
	 * @param from
	 * @param to
	 * @return
	 */
	public boolean isInConeAngle(ComplexAngle coneHalfAngle, ComplexAngle angle) {
		// need to "rotate" our gun to match the ship
		ComplexAngle larger = this.addAngle(coneHalfAngle);
		ComplexAngle smaller = this.subtractAngle(coneHalfAngle);
		return larger.compareTo(angle) > 0 && smaller.compareTo(angle) < 0;// signed angles

	}

	/**
	 * to show the round of errors.
	 * 
	 * @return
	 */
	public double length() {
		return sqrt(real * real + imag * imag);
	}

	/**
	 * I hope this is normalized... Or there will be trouble.
	 * 
	 * @return
	 */
	public double cos() {
		return real;
	}

	/**
	 * we are normlaized... Right!
	 * 
	 * @return
	 */
	public double sin() {
		return imag;
	}

	public double tan() {
		return imag / real;
	}

	/**
	 * 
	 * @return a rotation matrix
	 */
	public AffineTransform getRotationTransform() {
		double cos = real;
		double sin = -imag;//for the left handed coords for java2d. Note that a gl matrix would have this +
		return new AffineTransform(new double[] { cos, -sin, sin, cos});
	}

	/**
	 * degenrate cases when angles are PI apart. 
	 * @param c
	 * @param t
	 * @return
	 */
	public ComplexAngle interpolate(ComplexAngle c, double t) {
		double oneMinusT = 1 - t;
		double r = real * oneMinusT + c.real * t;
		double i = imag * oneMinusT + c.imag * t;
		ComplexAngle ca = new ComplexAngle(r, i);
		ca.normalize();// typically required here.
		return ca;
	}

	public void normalize() {
		double n = 1.0 / Math.sqrt(real * real + imag * imag);
		real *= n;
		imag *= n;
	}
	
	@Override
	public String toString() {
		return "ComplexAngle("+real+","+imag+"):"+length();
	}
	
	public static class Example extends JPanel implements MouseMotionListener{
		
		Point2D mouse=new Point2D.Double(0,0);
		ComplexAngle sweep=ComplexAngle.createAngle(1, 0);
		Point2D center=new Point2D.Double(100,100);
		ComplexAngle cone=ComplexAngle.createAngle(PI*2/45);//8 deg
		double t=.5;
		double dt=.02;
		
		public Example() {
			addMouseMotionListener(this);
			setBackground(Color.white);
			
		}
		
		@Override
		protected void paintComponent(Graphics g) {
			super.paintComponent(g);
			Graphics2D g2d=(Graphics2D)g;
		
			t+=dt;
			if(t>1){
				t=1;
				dt=-dt;
			}else if(t<0){
				t=0;
				dt=-dt;
			}
			
			ComplexAngle lookAt=ComplexAngle.angleTo(center, mouse);
	
			AffineTransform rotation=lookAt.getRotationTransform();
			AffineTransform af=AffineTransform.getTranslateInstance(center.getX(), center.getY());
			af.concatenate(rotation);
			
			AffineTransform oldTransform=g2d.getTransform();
			g2d.setTransform(af);
			g2d.setColor(Color.BLACK);
			paintDude(g2d);
			
			//now for sweeper. 
			if(sweep.compareTo(lookAt)<0){
				sweep.addAngleThis(ComplexAngle.DELTA_ANGLE);
				g2d.setColor(Color.RED);
			}else{
				sweep.subtractAngleThis(ComplexAngle.DELTA_ANGLE);
				g2d.setColor(Color.BLUE);
			}
			if(lookAt.isInConeAngle(cone, sweep)){
				g2d.setColor(Color.GREEN);
			}
			
			System.out.println(sweep);
			
			g2d.setTransform(oldTransform);
			
			drawLine(g2d,center,sweep,200);
			
			g2d.setColor(Color.GRAY);
			drawLine(g2d,center,lookAt.addAngle(cone),100);
			drawLine(g2d,center,lookAt.subtractAngle(cone),100);
			
			g2d.setColor(Color.CYAN);
			drawLine(g2d,center,sweep.interpolate(sweep.addAngle(ComplexAngle.RIGHT_ANGLE),t),50);
			drawLine(g2d,center,sweep.interpolate(sweep.subtractAngle(ComplexAngle.RIGHT_ANGLE),t),50);
			
		}
		
		/**
		 * paints a circle with a line from 0,0 to 10,0
		 */
		private void paintDude(Graphics2D g2d){
			g2d.draw(new Ellipse2D.Double(-10,-5,20,10));
			g2d.drawLine(0, 0, 30, 0);
			
		}
		
		private void drawLine(Graphics2D g2d,Point2D from,ComplexAngle angle,double l){
			//here we use the example that a complex number can just be interpreted as a unit vector in the direction its pointing. 
			//this is why, if we are normalized cos and sin are just the real and imag parts respectively. 
			g2d.drawLine((int)from.getX(),(int)from.getY(),(int)(l*angle.cos()+from.getX()), (int)(l*angle.sin()+from.getY()));
			
		}
		
		@Override
		public void mouseDragged(MouseEvent e) {
			center=new Point2D.Double(e.getX(),e.getY());
			
		}
		
		@Override
		public void mouseMoved(MouseEvent e) {
			mouse=new Point2D.Double(e.getX(),e.getY());
			
		}
		
	}

	public static void main(String[] args) {
		JFrame frame=new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		frame.setSize(500,500);
		
		Example example=new Example();
		frame.add(example);
		frame.setVisible(true);
		((Graphics2D)example.getGraphics()).addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
		while(true){
			try {
				Thread.sleep(16);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			example.repaint();
		}
	}
}

This is quite cool!

This is quite cool!

What you call a ComplexAngle, is also known as the left column of a 2D rotation Matrix.

The API doc of AffineTransform calls it a rotation vector,
http://docs.oracle.com/javase/7/docs/api/java/awt/geom/AffineTransform.html#rotate(double, double)

Anyway, that’s some nice code you got there. However I wanted to offer an alternative implementation.

class Vector {
    public static final Vector X_AXIS = new Vector(1,0);
    public static final Vector Y_AXIS = new Vector(0,1);
    
    public final double x, y;
    public Vector(double x, double y) {
        this.x = x;
        this.y = y;
    }
    //creates a Vector from polar coordinates
    public Vector fromPolar(double length, double angle) {
        return new Vector(Math.cos(angle)*length, Math.sin(angle)*length);
    }
    public Vector add(Vector v) {
        return new Vector(x+v.x, y+v.y);
    }
    public Vector sub(Vector v) {
        return new Vector(x-v.x, y-v.y);
    }
    public Vector mul(double d) {
        return new Vector(x*d, y*d);
    }
    public Vector neg() {
        return new Vector(-x, -y);
    }
    public double dotProduct(Vector v) {
        return x*v.x + y*v.y;
    }
    public double crossProduct(Vector v) {
        return x*v.y - y*v.x;
    }
    public double length() {
        return Math.sqrt(x*x+y*y);
    }
    public Vector normalize() {
        return mul(1/length());
    }
    public Vector rotate90() {
        return new Vector(-y, x);
    }
    public Vector rotate(Angle a) {
        return a.rotate(this);
    }
    public Vector rotateAround(Vector center, Angle angle) {
        return sub(center).rotate(angle).add(center);
    }
    public Vector rotateOpposite(Angle a) {
        return a.rotateOpposite(this);
    }
    public Vector rotate(double angle) {
        return new Angle(angle).rotate(this);
    }
    public Angle angle() {
        return Angle.fromVector(this);
    }
    public Angle angleTo(Vector v) {
        return v.angle().sub(angle());
    }
    @Override
    public String toString() {
        return "Vector("+x+", "+y+")";
    }
}

class Angle {
    public final double cos, sin;
    
    public Angle(double angle) {
        cos = Math.cos(angle);
        sin = Math.sin(angle);
    }
    private Angle(double cos, double sin) {
        this.cos = cos;
        this.sin = sin;
    }
    public static Angle fromVector(Vector v) {
        double length = v.length();
        return new Angle(v.x/length, v.y/length);
    }
    public Angle inverse() {
        return new Angle(cos, -sin);
    }
    public Angle add(Angle a) {
        return new Angle(cos*a.cos - sin*a.sin,
                         cos*a.sin + sin*a.cos);
    }
    public Angle sub(Angle a) {
        return add(a.inverse());
    }
    public Vector rotate(Vector v) {
        return new Vector(v.x*cos - v.y*sin,
                          v.x*sin + v.y*cos);
    }
    public Vector rotateOpposite(Vector v) {
        return new Vector( v.x*cos + v.y*sin,
                          -v.x*sin + v.y*cos);
    }
    public double toRadians() {
        return Math.atan2(sin,cos);
    }
    public double toDegrees() {
        return Math.toDegrees(toRadians());
    }
    @Override
    public String toString() {
        return "Angle " + toDegrees() + " degrees";
    }
}

class Camera {
    Vector pos;
    Angle orientation;
    double zoom;

    public Camera(Vector pos, Angle orientation, double zoom) {
        this.pos = pos;
        this.orientation = orientation;
        this.zoom = zoom;
    }
    public Camera(Vector pos, double orientation, double zoom) {
        this(pos, new Angle(orientation), zoom);
    }
    public Camera() {
        this(new Vector(0,0), 0, 1);
    }
    public Vector toScreenCoordinates(Vector v) {
        return v.sub(pos).rotateOpposite(orientation).mul(zoom);
    }
    public Vector toGameCoordinates(Vector v) {
        return pos.mul(1/zoom).rotate(orientation).add(pos);
    }
    public void zoom(double zoom) {
        zoom *= zoom;
    }
    public void rotate(Angle angle) {
        orientation = orientation.add(angle);
    }
    public void rotate(double angle) {
        rotate(new Angle(angle));
    }
    public void rotateAround(Vector center, Angle angle) {
        pos = pos.sub(center).rotate(angle).add(center);
        orientation = orientation.add(angle);
    }
    public void rotateAround(Vector center, double angle) {
        rotateAround(center, new Angle(angle));
    }
    public AffineTransform affineTransform() {
        AffineTransform at = AffineTransform.getScaleInstance(zoom, zoom);
        at.rotate(orientation.cos, -orientation.sin);
        at.translate(-pos.x, -pos.y);
        return at;
    }
}

    public void zoom(double zoom) {
-        zoom *= zoom;
+        this.zoom *= zoom;
    }

What you call a ComplexAngle, is also known as the left column of a 2D rotation Matrix.

The API doc of AffineTransform calls it a rotation vector,
http://docs.oracle.com/javase/7/docs/api/java/awt/geom/AffineTransform.html#rotate(double, double)

Anyway, that’s some nice code you got there. However I wanted to offer an alternative implementation.

class Vector {
    public static final Vector X_AXIS = new Vector(1,0);
    public static final Vector Y_AXIS = new Vector(0,1);
    
    public final double x, y;
    public Vector(double x, double y) {
        this.x = x;
        this.y = y;
    }
    //creates a Vector from polar coordinates
    public Vector fromPolar(double length, double angle) {
        return new Vector(Math.cos(angle)*length, Math.sin(angle)*length);
    }
    public Vector add(Vector v) {
        return new Vector(x+v.x, y+v.y);
    }
    public Vector sub(Vector v) {
        return new Vector(x-v.x, y-v.y);
    }
    public Vector mul(double d) {
        return new Vector(x*d, y*d);
    }
    public Vector neg() {
        return new Vector(-x, -y);
    }
    public double dotProduct(Vector v) {
        return x*v.x + y*v.y;
    }
    public double crossProduct(Vector v) {
        return x*v.y - y*v.x;
    }
    public double length() {
        return Math.sqrt(x*x+y*y);
    }
    public Vector normalize() {
        return mul(1/length());
    }
    public Vector rotate90() {
        return new Vector(-y, x);
    }
    public Vector rotate(Angle a) {
        return a.rotate(this);
    }
    public Vector rotateAround(Vector center, Angle angle) {
        return sub(center).rotate(angle).add(center);
    }
    public Vector rotateOpposite(Angle a) {
        return a.rotateOpposite(this);
    }
    public Vector rotate(double angle) {
        return new Angle(angle).rotate(this);
    }
    public Angle angle() {
        return Angle.fromVector(this);
    }
    public Angle angleTo(Vector v) {
        return v.angle().sub(angle());
    }
    @Override
    public String toString() {
        return "Vector("+x+", "+y+")";
    }
}

class Angle {
    public final double cos, sin;
    
    public Angle(double angle) {
        cos = Math.cos(angle);
        sin = Math.sin(angle);
    }
    private Angle(double cos, double sin) {
        this.cos = cos;
        this.sin = sin;
    }
    public static Angle fromVector(Vector v) {
        double length = v.length();
        return new Angle(v.x/length, v.y/length);
    }
    public Angle inverse() {
        return new Angle(cos, -sin);
    }
    public Angle add(Angle a) {
        return new Angle(cos*a.cos - sin*a.sin,
                         cos*a.sin + sin*a.cos);
    }
    public Angle sub(Angle a) {
        return add(a.inverse());
    }
    public Vector rotate(Vector v) {
        return new Vector(v.x*cos - v.y*sin,
                          v.x*sin + v.y*cos);
    }
    public Vector rotateOpposite(Vector v) {
        return new Vector( v.x*cos + v.y*sin,
                          -v.x*sin + v.y*cos);
    }
    public double toRadians() {
        return Math.atan2(sin,cos);
    }
    public double toDegrees() {
        return Math.toDegrees(toRadians());
    }
    @Override
    public String toString() {
        return "Angle " + toDegrees() + " degrees";
    }
}

class Camera {
    Vector pos;
    Angle orientation;
    double zoom;

    public Camera(Vector pos, Angle orientation, double zoom) {
        this.pos = pos;
        this.orientation = orientation;
        this.zoom = zoom;
    }
    public Camera(Vector pos, double orientation, double zoom) {
        this(pos, new Angle(orientation), zoom);
    }
    public Camera() {
        this(new Vector(0,0), 0, 1);
    }
    public Vector toScreenCoordinates(Vector v) {
        return v.sub(pos).rotateOpposite(orientation).mul(zoom);
    }
    public Vector toGameCoordinates(Vector v) {
        return pos.mul(1/zoom).rotate(orientation).add(pos);
    }
    public void zoom(double zoom) {
        zoom *= zoom;
    }
    public void rotate(Angle angle) {
        orientation = orientation.add(angle);
    }
    public void rotate(double angle) {
        rotate(new Angle(angle));
    }
    public void rotateAround(Vector center, Angle angle) {
        pos = pos.sub(center).rotate(angle).add(center);
        orientation = orientation.add(angle);
    }
    public void rotateAround(Vector center, double angle) {
        rotateAround(center, new Angle(angle));
    }
    public AffineTransform affineTransform() {
        AffineTransform at = AffineTransform.getScaleInstance(zoom, zoom);
        at.rotate(orientation.cos, -orientation.sin);
        at.translate(-pos.x, -pos.y);
        return at;
    }
}

    public void zoom(double zoom) {
-        zoom *= zoom;
+        this.zoom *= zoom;
    }

If I were ever to do 2D stuff I’d just abuse the mathematical types and merge complex numbers and vectors into a single type. I can’t think of any situations where the difference in symmetry would cause a problem. Something like this, but not immutable.

[quote=“delt0r,post:1,topic:41241”]
A pedant might say that you’re not avoiding trig, just concealing it via de Moivre’s theorem.

If I were ever to do 2D stuff I’d just abuse the mathematical types and merge complex numbers and vectors into a single type. I can’t think of any situations where the difference in symmetry would cause a problem. Something like this, but not immutable.

That’s one way of looking at it (starting from Euler’s might be easier though…haven’t thought this through). The other is that when you’re using angles and directly trig ops & identities that you’re working in an exponential or log mapped space when you could be working in linear.

[quote=“delt0r,post:1,topic:41241”]
A pedant might say that you’re not avoiding trig, just concealing it via de Moivre’s theorem.

That’s one way of looking at it (starting from Euler’s might be easier though…haven’t thought this through). The other is that when you’re using angles and directly trig ops & identities that you’re working in an exponential or log mapped space when you could be working in linear.

This looks like trig to me. Just with different variable names and concealment of trig operations.

If it walks like a trig and quacks like a trig, it’s a duck.

This looks like trig to me. Just with different variable names and concealment of trig operations.

If it walks like a trig and quacks like a trig, it’s a duck.

@HeroesGraveDev: It’s superficial. Most problems you don’t need to consider the angle or trig ops or identities…they’re magically built in to the negative signature (fancy way of saying e*e = -1). The “real” benefit here is not only cheaper operations but the fact that you’re adding a bunch of tools that allow you to look at the same problem in more ways.

@HeroesGraveDev: It’s superficial. Most problems you don’t need to consider the angle or trig ops or identities…they’re magically built in to the negative signature (fancy way of saying e*e = -1). The “real” benefit here is not only cheaper operations but the fact that you’re adding a bunch of tools that allow you to look at the same problem in more ways.

My only concern is that handling these objects is putting both stress on the GC (stack allocation is not perfect yet) and on code verbosity (due to the lack of operator overloading). To me it feels like I’m forced to do ‘boxing and unboxing’ that angle every time I access it. I think that solely for that reason I’d stick to ‘float angle’ in most of the cases. In C++ it’d be a lot less of a burden to make the switch.