package com.jcomeau; import java.math.BigDecimal; public class Complex { public static final int mode = BigDecimal.ROUND_HALF_EVEN; double x = 0, y = 0; BigDecimal xBig = null, yBig = null; public static final BigDecimal two = new BigDecimal(2.0); public Complex(double x, double y) { this.x = x; this.y = y; } public Complex(BigDecimal x, BigDecimal y) { this.xBig = x; this.yBig = y; } public Complex squared() { int scale; if (xBig == null) { return new Complex((x * x) - (y * y), 2 * x * y); } else { scale = xBig.scale(); return new Complex(xBig.multiply(xBig).subtract( yBig.multiply(yBig)).setScale(scale, mode), two.multiply(xBig).multiply(yBig).setScale(scale, mode)); } } public Complex add(Complex addend) { Complex sum; if (xBig == null) { return new Complex(x + addend.x, y + addend.y); } else { sum = new Complex(xBig.add(addend.xBig), yBig.add(addend.yBig)); //Common.debug("sum=" + sum); return sum; } } public double abs() { return Math.sqrt((x * x) + (y * y)); } /* when the absolute value is being compared to something, as in the * case of the Mandelbrot set, we can avoid the cost of the square root * by just returning x squared + y squared and comparing to z squared * * specify a BigDecimal arg to force use of that method */ public double absSquared() { return (x * x) + (y * y); } public double absSquared(BigDecimal any) { if (xBig == null) return 0; else return (xBig.multiply(xBig)).add(yBig.multiply(yBig)).doubleValue(); } public String toString() { if (xBig == null) return "(" + x + ", " + y + ")"; else return "(" + xBig + ", " + yBig + ")"; } public static void main(String[] args) { if (args.length != 2) { System.err.println("must specify x and y"); } else { Complex z = new Complex(Double.parseDouble(args[0]), Double.parseDouble(args[1])); System.out.println("z = " + z); System.out.println("z.squared() = " + z.squared()); z = new Complex(new BigDecimal(z.x), new BigDecimal(z.y)); System.out.println("z = " + z); System.out.println("z.squared() = " + z.squared()); } } }