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