ComplexMathUtils { public static ComplexNumber sqrt(final ComplexNumber z) { ArgumentChecker.notNull(z, "z"); final double c = z.getReal(); final double d = z.getImaginary(); if (c == 0.0 && d == 0.0) { return z; } double w; if (Math.abs(c) > Math.abs(d)) { final double dOverC = d / c; w = Math.sqrt(Math.abs(c)) * Math.sqrt((1 + Math.sqrt(1 + dOverC * dOverC)) / 2); } else { final double cOverD = c / d; w = Math.sqrt(Math.abs(d)) * Math.sqrt((Math.abs(cOverD) + Math.sqrt(1 + cOverD * cOverD)) / 2); } if (c >= 0.0) { return new ComplexNumber(w, d / 2 / w); } if (d >= 0.0) { return new ComplexNumber(d / 2 / w, w); } return new ComplexNumber(-d / 2 / w, -w); }  static ComplexNumber add(final ComplexNumber z1, final ComplexNumber z2); static ComplexNumber add(final ComplexNumber... z); static ComplexNumber add(final ComplexNumber z, final double x); static ComplexNumber add(final double x, final ComplexNumber z); static double arg(final ComplexNumber z); static ComplexNumber conjugate(final ComplexNumber z); static ComplexNumber divide(final ComplexNumber z1, final ComplexNumber z2); static ComplexNumber divide(final ComplexNumber z, final double x); static ComplexNumber divide(final double x, final ComplexNumber z); static ComplexNumber exp(final ComplexNumber z); static ComplexNumber inverse(final ComplexNumber z); static ComplexNumber log(final ComplexNumber z); static double mod(final ComplexNumber z); static ComplexNumber square(final ComplexNumber z); static ComplexNumber multiply(final ComplexNumber z1, final ComplexNumber z2); static ComplexNumber multiply(final ComplexNumber... z); static ComplexNumber multiply(final double x, final ComplexNumber... z); static ComplexNumber multiply(final ComplexNumber z, final double x); static ComplexNumber multiply(final double x, final ComplexNumber z); static ComplexNumber pow(final ComplexNumber z1, final ComplexNumber z2); static ComplexNumber pow(final ComplexNumber z, final double x); static ComplexNumber pow(final double x, final ComplexNumber z); static ComplexNumber sqrt(final ComplexNumber z); static ComplexNumber subtract(final ComplexNumber z1, final ComplexNumber z2); static ComplexNumber subtract(final ComplexNumber z, final double x); static ComplexNumber subtract(final double x, final ComplexNumber z);  }
@Test public void testSqrt() { ComplexNumber z1 = new ComplexNumber(3, -2); ComplexNumber z2 = new ComplexNumber(-3, 4); ComplexNumber z3 = new ComplexNumber(-3, -4); ComplexNumber rZ1 = ComplexMathUtils.sqrt(z1); ComplexNumber rZ2 = ComplexMathUtils.sqrt(z2); ComplexNumber rZ3 = ComplexMathUtils.sqrt(z3); assertComplexEquals(ComplexMathUtils.pow(z1, 0.5), rZ1); assertComplexEquals(ComplexMathUtils.pow(z2, 0.5), rZ2); assertComplexEquals(ComplexMathUtils.pow(z3, 0.5), rZ3); assertComplexEquals(z1, ComplexMathUtils.square(rZ1)); assertComplexEquals(z2, ComplexMathUtils.square(rZ2)); assertComplexEquals(z3, ComplexMathUtils.square(rZ3)); }