public class Complex_adaptive { private double d1; private double d2; private boolean cart; private void switch_to_polar() { if(!cart) return; double r = Math.sqrt(d1 * d1 + d2 * d2); double theta = Math.atan2(d1, d2); d1 = r; d2 = theta; cart = false; } private void switch_to_cartesian() { if(cart) return; double a = d1 * Math.cos(d2); double b = d1 * Math.sin(d2); d1 = a; d2 = b; cart = true; } private Complex_adaptive(double d1, double d2, boolean cart) { this.d1 = d1; this.d2 = d2; this.cart = cart; if(!cart && d1 < 0) { d1 = -d1; d2 = d2 + Math.PI; } d2 -= 2 * Math.PI * (d2 / (2 * Math.PI)); // theta = theta % 2*PI if(d2 > Math.PI) d2 -= Math.PI * 2; } public Complex_adaptive Complex_from_cartesian(double a, double b) { return new Complex_adaptive(a, b, true); } public Complex_adaptive Complex_from_polar(double a, double b) { return new Complex_adaptive(a, b, false); } public double getA() { switch_to_cartesian(); return d1; } public double getB() { switch_to_cartesian(); return d2; } public double getR() { switch_to_polar(); return d1; } public double getTheta() { switch_to_polar(); return d2; } public Complex_adaptive add(Complex_adaptive c) { return Complex_from_cartesian(getA() + c.getA(), getB() + c.getB()); } public Complex_adaptive multiply(Complex_adaptive c) { return Complex_from_polar(getR() * c.getR(), getTheta() + c.getTheta()); } }