001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.math3.complex;
019
020import java.io.Serializable;
021import java.util.ArrayList;
022import java.util.List;
023
024import org.apache.commons.math3.FieldElement;
025import org.apache.commons.math3.exception.NotPositiveException;
026import org.apache.commons.math3.exception.NullArgumentException;
027import org.apache.commons.math3.exception.util.LocalizedFormats;
028import org.apache.commons.math3.util.FastMath;
029import org.apache.commons.math3.util.MathUtils;
030import org.apache.commons.math3.util.Precision;
031
032/**
033 * Representation of a Complex number, i.e. a number which has both a
034 * real and imaginary part.
035 * <br/>
036 * Implementations of arithmetic operations handle {@code NaN} and
037 * infinite values according to the rules for {@link java.lang.Double}, i.e.
038 * {@link #equals} is an equivalence relation for all instances that have
039 * a {@code NaN} in either real or imaginary part, e.g. the following are
040 * considered equal:
041 * <ul>
042 *  <li>{@code 1 + NaNi}</li>
043 *  <li>{@code NaN + i}</li>
044 *  <li>{@code NaN + NaNi}</li>
045 * </ul>
046 * Note that this is in contradiction with the IEEE-754 standard for floating
047 * point numbers (according to which the test {@code x == x} must fail if
048 * {@code x} is {@code NaN}). The method
049 * {@link org.apache.commons.math3.util.Precision#equals(double,double,int)
050 * equals for primitive double} in {@link org.apache.commons.math3.util.Precision}
051 * conforms with IEEE-754 while this class conforms with the standard behavior
052 * for Java object types.
053 * <br/>
054 * Implements Serializable since 2.0
055 *
056 * @version $Id: Complex.java 1591835 2014-05-02 09:04:01Z tn $
057 */
058public class Complex implements FieldElement<Complex>, Serializable  {
059    /** The square root of -1. A number representing "0.0 + 1.0i" */
060    public static final Complex I = new Complex(0.0, 1.0);
061    // CHECKSTYLE: stop ConstantName
062    /** A complex number representing "NaN + NaNi" */
063    public static final Complex NaN = new Complex(Double.NaN, Double.NaN);
064    // CHECKSTYLE: resume ConstantName
065    /** A complex number representing "+INF + INFi" */
066    public static final Complex INF = new Complex(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
067    /** A complex number representing "1.0 + 0.0i" */
068    public static final Complex ONE = new Complex(1.0, 0.0);
069    /** A complex number representing "0.0 + 0.0i" */
070    public static final Complex ZERO = new Complex(0.0, 0.0);
071
072    /** Serializable version identifier */
073    private static final long serialVersionUID = -6195664516687396620L;
074
075    /** The imaginary part. */
076    private final double imaginary;
077    /** The real part. */
078    private final double real;
079    /** Record whether this complex number is equal to NaN. */
080    private final transient boolean isNaN;
081    /** Record whether this complex number is infinite. */
082    private final transient boolean isInfinite;
083
084    /**
085     * Create a complex number given only the real part.
086     *
087     * @param real Real part.
088     */
089    public Complex(double real) {
090        this(real, 0.0);
091    }
092
093    /**
094     * Create a complex number given the real and imaginary parts.
095     *
096     * @param real Real part.
097     * @param imaginary Imaginary part.
098     */
099    public Complex(double real, double imaginary) {
100        this.real = real;
101        this.imaginary = imaginary;
102
103        isNaN = Double.isNaN(real) || Double.isNaN(imaginary);
104        isInfinite = !isNaN &&
105            (Double.isInfinite(real) || Double.isInfinite(imaginary));
106    }
107
108    /**
109     * Return the absolute value of this complex number.
110     * Returns {@code NaN} if either real or imaginary part is {@code NaN}
111     * and {@code Double.POSITIVE_INFINITY} if neither part is {@code NaN},
112     * but at least one part is infinite.
113     *
114     * @return the absolute value.
115     */
116    public double abs() {
117        if (isNaN) {
118            return Double.NaN;
119        }
120        if (isInfinite()) {
121            return Double.POSITIVE_INFINITY;
122        }
123        if (FastMath.abs(real) < FastMath.abs(imaginary)) {
124            if (imaginary == 0.0) {
125                return FastMath.abs(real);
126            }
127            double q = real / imaginary;
128            return FastMath.abs(imaginary) * FastMath.sqrt(1 + q * q);
129        } else {
130            if (real == 0.0) {
131                return FastMath.abs(imaginary);
132            }
133            double q = imaginary / real;
134            return FastMath.abs(real) * FastMath.sqrt(1 + q * q);
135        }
136    }
137
138    /**
139     * Returns a {@code Complex} whose value is
140     * {@code (this + addend)}.
141     * Uses the definitional formula
142     * <pre>
143     *  <code>
144     *   (a + bi) + (c + di) = (a+c) + (b+d)i
145     *  </code>
146     * </pre>
147     * <br/>
148     * If either {@code this} or {@code addend} has a {@code NaN} value in
149     * either part, {@link #NaN} is returned; otherwise {@code Infinite}
150     * and {@code NaN} values are returned in the parts of the result
151     * according to the rules for {@link java.lang.Double} arithmetic.
152     *
153     * @param  addend Value to be added to this {@code Complex}.
154     * @return {@code this + addend}.
155     * @throws NullArgumentException if {@code addend} is {@code null}.
156     */
157    public Complex add(Complex addend) throws NullArgumentException {
158        MathUtils.checkNotNull(addend);
159        if (isNaN || addend.isNaN) {
160            return NaN;
161        }
162
163        return createComplex(real + addend.getReal(),
164                             imaginary + addend.getImaginary());
165    }
166
167    /**
168     * Returns a {@code Complex} whose value is {@code (this + addend)},
169     * with {@code addend} interpreted as a real number.
170     *
171     * @param addend Value to be added to this {@code Complex}.
172     * @return {@code this + addend}.
173     * @see #add(Complex)
174     */
175    public Complex add(double addend) {
176        if (isNaN || Double.isNaN(addend)) {
177            return NaN;
178        }
179
180        return createComplex(real + addend, imaginary);
181    }
182
183     /**
184     * Return the conjugate of this complex number.
185     * The conjugate of {@code a + bi} is {@code a - bi}.
186     * <br/>
187     * {@link #NaN} is returned if either the real or imaginary
188     * part of this Complex number equals {@code Double.NaN}.
189     * <br/>
190     * If the imaginary part is infinite, and the real part is not
191     * {@code NaN}, the returned value has infinite imaginary part
192     * of the opposite sign, e.g. the conjugate of
193     * {@code 1 + POSITIVE_INFINITY i} is {@code 1 - NEGATIVE_INFINITY i}.
194     *
195     * @return the conjugate of this Complex object.
196     */
197    public Complex conjugate() {
198        if (isNaN) {
199            return NaN;
200        }
201
202        return createComplex(real, -imaginary);
203    }
204
205    /**
206     * Returns a {@code Complex} whose value is
207     * {@code (this / divisor)}.
208     * Implements the definitional formula
209     * <pre>
210     *  <code>
211     *    a + bi          ac + bd + (bc - ad)i
212     *    ----------- = -------------------------
213     *    c + di         c<sup>2</sup> + d<sup>2</sup>
214     *  </code>
215     * </pre>
216     * but uses
217     * <a href="http://doi.acm.org/10.1145/1039813.1039814">
218     * prescaling of operands</a> to limit the effects of overflows and
219     * underflows in the computation.
220     * <br/>
221     * {@code Infinite} and {@code NaN} values are handled according to the
222     * following rules, applied in the order presented:
223     * <ul>
224     *  <li>If either {@code this} or {@code divisor} has a {@code NaN} value
225     *   in either part, {@link #NaN} is returned.
226     *  </li>
227     *  <li>If {@code divisor} equals {@link #ZERO}, {@link #NaN} is returned.
228     *  </li>
229     *  <li>If {@code this} and {@code divisor} are both infinite,
230     *   {@link #NaN} is returned.
231     *  </li>
232     *  <li>If {@code this} is finite (i.e., has no {@code Infinite} or
233     *   {@code NaN} parts) and {@code divisor} is infinite (one or both parts
234     *   infinite), {@link #ZERO} is returned.
235     *  </li>
236     *  <li>If {@code this} is infinite and {@code divisor} is finite,
237     *   {@code NaN} values are returned in the parts of the result if the
238     *   {@link java.lang.Double} rules applied to the definitional formula
239     *   force {@code NaN} results.
240     *  </li>
241     * </ul>
242     *
243     * @param divisor Value by which this {@code Complex} is to be divided.
244     * @return {@code this / divisor}.
245     * @throws NullArgumentException if {@code divisor} is {@code null}.
246     */
247    public Complex divide(Complex divisor)
248        throws NullArgumentException {
249        MathUtils.checkNotNull(divisor);
250        if (isNaN || divisor.isNaN) {
251            return NaN;
252        }
253
254        final double c = divisor.getReal();
255        final double d = divisor.getImaginary();
256        if (c == 0.0 && d == 0.0) {
257            return NaN;
258        }
259
260        if (divisor.isInfinite() && !isInfinite()) {
261            return ZERO;
262        }
263
264        if (FastMath.abs(c) < FastMath.abs(d)) {
265            double q = c / d;
266            double denominator = c * q + d;
267            return createComplex((real * q + imaginary) / denominator,
268                (imaginary * q - real) / denominator);
269        } else {
270            double q = d / c;
271            double denominator = d * q + c;
272            return createComplex((imaginary * q + real) / denominator,
273                (imaginary - real * q) / denominator);
274        }
275    }
276
277    /**
278     * Returns a {@code Complex} whose value is {@code (this / divisor)},
279     * with {@code divisor} interpreted as a real number.
280     *
281     * @param  divisor Value by which this {@code Complex} is to be divided.
282     * @return {@code this / divisor}.
283     * @see #divide(Complex)
284     */
285    public Complex divide(double divisor) {
286        if (isNaN || Double.isNaN(divisor)) {
287            return NaN;
288        }
289        if (divisor == 0d) {
290            return NaN;
291        }
292        if (Double.isInfinite(divisor)) {
293            return !isInfinite() ? ZERO : NaN;
294        }
295        return createComplex(real / divisor,
296                             imaginary  / divisor);
297    }
298
299    /** {@inheritDoc} */
300    public Complex reciprocal() {
301        if (isNaN) {
302            return NaN;
303        }
304
305        if (real == 0.0 && imaginary == 0.0) {
306            return INF;
307        }
308
309        if (isInfinite) {
310            return ZERO;
311        }
312
313        if (FastMath.abs(real) < FastMath.abs(imaginary)) {
314            double q = real / imaginary;
315            double scale = 1. / (real * q + imaginary);
316            return createComplex(scale * q, -scale);
317        } else {
318            double q = imaginary / real;
319            double scale = 1. / (imaginary * q + real);
320            return createComplex(scale, -scale * q);
321        }
322    }
323
324    /**
325     * Test for equality with another object.
326     * If both the real and imaginary parts of two complex numbers
327     * are exactly the same, and neither is {@code Double.NaN}, the two
328     * Complex objects are considered to be equal.
329     * The behavior is the same as for JDK's {@link Double#equals(Object)
330     * Double}:
331     * <ul>
332     *  <li>All {@code NaN} values are considered to be equal,
333     *   i.e, if either (or both) real and imaginary parts of the complex
334     *   number are equal to {@code Double.NaN}, the complex number is equal
335     *   to {@code NaN}.
336     *  </li>
337     *  <li>
338     *   Instances constructed with different representations of zero (i.e.
339     *   either "0" or "-0") are <em>not</em> considered to be equal.
340     *  </li>
341     * </ul>
342     *
343     * @param other Object to test for equality with this instance.
344     * @return {@code true} if the objects are equal, {@code false} if object
345     * is {@code null}, not an instance of {@code Complex}, or not equal to
346     * this instance.
347     */
348    @Override
349    public boolean equals(Object other) {
350        if (this == other) {
351            return true;
352        }
353        if (other instanceof Complex){
354            Complex c = (Complex) other;
355            if (c.isNaN) {
356                return isNaN;
357            } else {
358                return MathUtils.equals(real, c.real) &&
359                    MathUtils.equals(imaginary, c.imaginary);
360            }
361        }
362        return false;
363    }
364
365    /**
366     * Test for the floating-point equality between Complex objects.
367     * It returns {@code true} if both arguments are equal or within the
368     * range of allowed error (inclusive).
369     *
370     * @param x First value (cannot be {@code null}).
371     * @param y Second value (cannot be {@code null}).
372     * @param maxUlps {@code (maxUlps - 1)} is the number of floating point
373     * values between the real (resp. imaginary) parts of {@code x} and
374     * {@code y}.
375     * @return {@code true} if there are fewer than {@code maxUlps} floating
376     * point values between the real (resp. imaginary) parts of {@code x}
377     * and {@code y}.
378     *
379     * @see Precision#equals(double,double,int)
380     * @since 3.3
381     */
382    public static boolean equals(Complex x, Complex y, int maxUlps) {
383        return Precision.equals(x.real, y.real, maxUlps) &&
384            Precision.equals(x.imaginary, y.imaginary, maxUlps);
385    }
386
387    /**
388     * Returns {@code true} iff the values are equal as defined by
389     * {@link #equals(Complex,Complex,int) equals(x, y, 1)}.
390     *
391     * @param x First value (cannot be {@code null}).
392     * @param y Second value (cannot be {@code null}).
393     * @return {@code true} if the values are equal.
394     *
395     * @since 3.3
396     */
397    public static boolean equals(Complex x, Complex y) {
398        return equals(x, y, 1);
399    }
400
401    /**
402     * Returns {@code true} if, both for the real part and for the imaginary
403     * part, there is no double value strictly between the arguments or the
404     * difference between them is within the range of allowed error
405     * (inclusive).
406     *
407     * @param x First value (cannot be {@code null}).
408     * @param y Second value (cannot be {@code null}).
409     * @param eps Amount of allowed absolute error.
410     * @return {@code true} if the values are two adjacent floating point
411     * numbers or they are within range of each other.
412     *
413     * @see Precision#equals(double,double,double)
414     * @since 3.3
415     */
416    public static boolean equals(Complex x, Complex y, double eps) {
417        return Precision.equals(x.real, y.real, eps) &&
418            Precision.equals(x.imaginary, y.imaginary, eps);
419    }
420
421    /**
422     * Returns {@code true} if, both for the real part and for the imaginary
423     * part, there is no double value strictly between the arguments or the
424     * relative difference between them is smaller or equal to the given
425     * tolerance.
426     *
427     * @param x First value (cannot be {@code null}).
428     * @param y Second value (cannot be {@code null}).
429     * @param eps Amount of allowed relative error.
430     * @return {@code true} if the values are two adjacent floating point
431     * numbers or they are within range of each other.
432     *
433     * @see Precision#equalsWithRelativeTolerance(double,double,double)
434     * @since 3.3
435     */
436    public static boolean equalsWithRelativeTolerance(Complex x, Complex y,
437                                                      double eps) {
438        return Precision.equalsWithRelativeTolerance(x.real, y.real, eps) &&
439            Precision.equalsWithRelativeTolerance(x.imaginary, y.imaginary, eps);
440    }
441
442    /**
443     * Get a hashCode for the complex number.
444     * Any {@code Double.NaN} value in real or imaginary part produces
445     * the same hash code {@code 7}.
446     *
447     * @return a hash code value for this object.
448     */
449    @Override
450    public int hashCode() {
451        if (isNaN) {
452            return 7;
453        }
454        return 37 * (17 * MathUtils.hash(imaginary) +
455            MathUtils.hash(real));
456    }
457
458    /**
459     * Access the imaginary part.
460     *
461     * @return the imaginary part.
462     */
463    public double getImaginary() {
464        return imaginary;
465    }
466
467    /**
468     * Access the real part.
469     *
470     * @return the real part.
471     */
472    public double getReal() {
473        return real;
474    }
475
476    /**
477     * Checks whether either or both parts of this complex number is
478     * {@code NaN}.
479     *
480     * @return true if either or both parts of this complex number is
481     * {@code NaN}; false otherwise.
482     */
483    public boolean isNaN() {
484        return isNaN;
485    }
486
487    /**
488     * Checks whether either the real or imaginary part of this complex number
489     * takes an infinite value (either {@code Double.POSITIVE_INFINITY} or
490     * {@code Double.NEGATIVE_INFINITY}) and neither part
491     * is {@code NaN}.
492     *
493     * @return true if one or both parts of this complex number are infinite
494     * and neither part is {@code NaN}.
495     */
496    public boolean isInfinite() {
497        return isInfinite;
498    }
499
500    /**
501     * Returns a {@code Complex} whose value is {@code this * factor}.
502     * Implements preliminary checks for {@code NaN} and infinity followed by
503     * the definitional formula:
504     * <pre>
505     *  <code>
506     *   (a + bi)(c + di) = (ac - bd) + (ad + bc)i
507     *  </code>
508     * </pre>
509     * Returns {@link #NaN} if either {@code this} or {@code factor} has one or
510     * more {@code NaN} parts.
511     * <br/>
512     * Returns {@link #INF} if neither {@code this} nor {@code factor} has one
513     * or more {@code NaN} parts and if either {@code this} or {@code factor}
514     * has one or more infinite parts (same result is returned regardless of
515     * the sign of the components).
516     * <br/>
517     * Returns finite values in components of the result per the definitional
518     * formula in all remaining cases.
519     *
520     * @param  factor value to be multiplied by this {@code Complex}.
521     * @return {@code this * factor}.
522     * @throws NullArgumentException if {@code factor} is {@code null}.
523     */
524    public Complex multiply(Complex factor)
525        throws NullArgumentException {
526        MathUtils.checkNotNull(factor);
527        if (isNaN || factor.isNaN) {
528            return NaN;
529        }
530        if (Double.isInfinite(real) ||
531            Double.isInfinite(imaginary) ||
532            Double.isInfinite(factor.real) ||
533            Double.isInfinite(factor.imaginary)) {
534            // we don't use isInfinite() to avoid testing for NaN again
535            return INF;
536        }
537        return createComplex(real * factor.real - imaginary * factor.imaginary,
538                             real * factor.imaginary + imaginary * factor.real);
539    }
540
541    /**
542     * Returns a {@code Complex} whose value is {@code this * factor}, with {@code factor}
543     * interpreted as a integer number.
544     *
545     * @param  factor value to be multiplied by this {@code Complex}.
546     * @return {@code this * factor}.
547     * @see #multiply(Complex)
548     */
549    public Complex multiply(final int factor) {
550        if (isNaN) {
551            return NaN;
552        }
553        if (Double.isInfinite(real) ||
554            Double.isInfinite(imaginary)) {
555            return INF;
556        }
557        return createComplex(real * factor, imaginary * factor);
558    }
559
560    /**
561     * Returns a {@code Complex} whose value is {@code this * factor}, with {@code factor}
562     * interpreted as a real number.
563     *
564     * @param  factor value to be multiplied by this {@code Complex}.
565     * @return {@code this * factor}.
566     * @see #multiply(Complex)
567     */
568    public Complex multiply(double factor) {
569        if (isNaN || Double.isNaN(factor)) {
570            return NaN;
571        }
572        if (Double.isInfinite(real) ||
573            Double.isInfinite(imaginary) ||
574            Double.isInfinite(factor)) {
575            // we don't use isInfinite() to avoid testing for NaN again
576            return INF;
577        }
578        return createComplex(real * factor, imaginary * factor);
579    }
580
581    /**
582     * Returns a {@code Complex} whose value is {@code (-this)}.
583     * Returns {@code NaN} if either real or imaginary
584     * part of this Complex number equals {@code Double.NaN}.
585     *
586     * @return {@code -this}.
587     */
588    public Complex negate() {
589        if (isNaN) {
590            return NaN;
591        }
592
593        return createComplex(-real, -imaginary);
594    }
595
596    /**
597     * Returns a {@code Complex} whose value is
598     * {@code (this - subtrahend)}.
599     * Uses the definitional formula
600     * <pre>
601     *  <code>
602     *   (a + bi) - (c + di) = (a-c) + (b-d)i
603     *  </code>
604     * </pre>
605     * If either {@code this} or {@code subtrahend} has a {@code NaN]} value in either part,
606     * {@link #NaN} is returned; otherwise infinite and {@code NaN} values are
607     * returned in the parts of the result according to the rules for
608     * {@link java.lang.Double} arithmetic.
609     *
610     * @param  subtrahend value to be subtracted from this {@code Complex}.
611     * @return {@code this - subtrahend}.
612     * @throws NullArgumentException if {@code subtrahend} is {@code null}.
613     */
614    public Complex subtract(Complex subtrahend)
615        throws NullArgumentException {
616        MathUtils.checkNotNull(subtrahend);
617        if (isNaN || subtrahend.isNaN) {
618            return NaN;
619        }
620
621        return createComplex(real - subtrahend.getReal(),
622                             imaginary - subtrahend.getImaginary());
623    }
624
625    /**
626     * Returns a {@code Complex} whose value is
627     * {@code (this - subtrahend)}.
628     *
629     * @param  subtrahend value to be subtracted from this {@code Complex}.
630     * @return {@code this - subtrahend}.
631     * @see #subtract(Complex)
632     */
633    public Complex subtract(double subtrahend) {
634        if (isNaN || Double.isNaN(subtrahend)) {
635            return NaN;
636        }
637        return createComplex(real - subtrahend, imaginary);
638    }
639
640    /**
641     * Compute the
642     * <a href="http://mathworld.wolfram.com/InverseCosine.html" TARGET="_top">
643     * inverse cosine</a> of this complex number.
644     * Implements the formula:
645     * <pre>
646     *  <code>
647     *   acos(z) = -i (log(z + i (sqrt(1 - z<sup>2</sup>))))
648     *  </code>
649     * </pre>
650     * Returns {@link Complex#NaN} if either real or imaginary part of the
651     * input argument is {@code NaN} or infinite.
652     *
653     * @return the inverse cosine of this complex number.
654     * @since 1.2
655     */
656    public Complex acos() {
657        if (isNaN) {
658            return NaN;
659        }
660
661        return this.add(this.sqrt1z().multiply(I)).log().multiply(I.negate());
662    }
663
664    /**
665     * Compute the
666     * <a href="http://mathworld.wolfram.com/InverseSine.html" TARGET="_top">
667     * inverse sine</a> of this complex number.
668     * Implements the formula:
669     * <pre>
670     *  <code>
671     *   asin(z) = -i (log(sqrt(1 - z<sup>2</sup>) + iz))
672     *  </code>
673     * </pre>
674     * Returns {@link Complex#NaN} if either real or imaginary part of the
675     * input argument is {@code NaN} or infinite.
676     *
677     * @return the inverse sine of this complex number.
678     * @since 1.2
679     */
680    public Complex asin() {
681        if (isNaN) {
682            return NaN;
683        }
684
685        return sqrt1z().add(this.multiply(I)).log().multiply(I.negate());
686    }
687
688    /**
689     * Compute the
690     * <a href="http://mathworld.wolfram.com/InverseTangent.html" TARGET="_top">
691     * inverse tangent</a> of this complex number.
692     * Implements the formula:
693     * <pre>
694     *  <code>
695     *   atan(z) = (i/2) log((i + z)/(i - z))
696     *  </code>
697     * </pre>
698     * Returns {@link Complex#NaN} if either real or imaginary part of the
699     * input argument is {@code NaN} or infinite.
700     *
701     * @return the inverse tangent of this complex number
702     * @since 1.2
703     */
704    public Complex atan() {
705        if (isNaN) {
706            return NaN;
707        }
708
709        return this.add(I).divide(I.subtract(this)).log()
710                .multiply(I.divide(createComplex(2.0, 0.0)));
711    }
712
713    /**
714     * Compute the
715     * <a href="http://mathworld.wolfram.com/Cosine.html" TARGET="_top">
716     * cosine</a>
717     * of this complex number.
718     * Implements the formula:
719     * <pre>
720     *  <code>
721     *   cos(a + bi) = cos(a)cosh(b) - sin(a)sinh(b)i
722     *  </code>
723     * </pre>
724     * where the (real) functions on the right-hand side are
725     * {@link FastMath#sin}, {@link FastMath#cos},
726     * {@link FastMath#cosh} and {@link FastMath#sinh}.
727     * <br/>
728     * Returns {@link Complex#NaN} if either real or imaginary part of the
729     * input argument is {@code NaN}.
730     * <br/>
731     * Infinite values in real or imaginary parts of the input may result in
732     * infinite or NaN values returned in parts of the result.
733     * <pre>
734     *  Examples:
735     *  <code>
736     *   cos(1 &plusmn; INFINITY i) = 1 &#x2213; INFINITY i
737     *   cos(&plusmn;INFINITY + i) = NaN + NaN i
738     *   cos(&plusmn;INFINITY &plusmn; INFINITY i) = NaN + NaN i
739     *  </code>
740     * </pre>
741     *
742     * @return the cosine of this complex number.
743     * @since 1.2
744     */
745    public Complex cos() {
746        if (isNaN) {
747            return NaN;
748        }
749
750        return createComplex(FastMath.cos(real) * FastMath.cosh(imaginary),
751                             -FastMath.sin(real) * FastMath.sinh(imaginary));
752    }
753
754    /**
755     * Compute the
756     * <a href="http://mathworld.wolfram.com/HyperbolicCosine.html" TARGET="_top">
757     * hyperbolic cosine</a> of this complex number.
758     * Implements the formula:
759     * <pre>
760     *  <code>
761     *   cosh(a + bi) = cosh(a)cos(b) + sinh(a)sin(b)i}
762     *  </code>
763     * </pre>
764     * where the (real) functions on the right-hand side are
765     * {@link FastMath#sin}, {@link FastMath#cos},
766     * {@link FastMath#cosh} and {@link FastMath#sinh}.
767     * <br/>
768     * Returns {@link Complex#NaN} if either real or imaginary part of the
769     * input argument is {@code NaN}.
770     * <br/>
771     * Infinite values in real or imaginary parts of the input may result in
772     * infinite or NaN values returned in parts of the result.
773     * <pre>
774     *  Examples:
775     *  <code>
776     *   cosh(1 &plusmn; INFINITY i) = NaN + NaN i
777     *   cosh(&plusmn;INFINITY + i) = INFINITY &plusmn; INFINITY i
778     *   cosh(&plusmn;INFINITY &plusmn; INFINITY i) = NaN + NaN i
779     *  </code>
780     * </pre>
781     *
782     * @return the hyperbolic cosine of this complex number.
783     * @since 1.2
784     */
785    public Complex cosh() {
786        if (isNaN) {
787            return NaN;
788        }
789
790        return createComplex(FastMath.cosh(real) * FastMath.cos(imaginary),
791                             FastMath.sinh(real) * FastMath.sin(imaginary));
792    }
793
794    /**
795     * Compute the
796     * <a href="http://mathworld.wolfram.com/ExponentialFunction.html" TARGET="_top">
797     * exponential function</a> of this complex number.
798     * Implements the formula:
799     * <pre>
800     *  <code>
801     *   exp(a + bi) = exp(a)cos(b) + exp(a)sin(b)i
802     *  </code>
803     * </pre>
804     * where the (real) functions on the right-hand side are
805     * {@link FastMath#exp}, {@link FastMath#cos}, and
806     * {@link FastMath#sin}.
807     * <br/>
808     * Returns {@link Complex#NaN} if either real or imaginary part of the
809     * input argument is {@code NaN}.
810     * <br/>
811     * Infinite values in real or imaginary parts of the input may result in
812     * infinite or NaN values returned in parts of the result.
813     * <pre>
814     *  Examples:
815     *  <code>
816     *   exp(1 &plusmn; INFINITY i) = NaN + NaN i
817     *   exp(INFINITY + i) = INFINITY + INFINITY i
818     *   exp(-INFINITY + i) = 0 + 0i
819     *   exp(&plusmn;INFINITY &plusmn; INFINITY i) = NaN + NaN i
820     *  </code>
821     * </pre>
822     *
823     * @return <code><i>e</i><sup>this</sup></code>.
824     * @since 1.2
825     */
826    public Complex exp() {
827        if (isNaN) {
828            return NaN;
829        }
830
831        double expReal = FastMath.exp(real);
832        return createComplex(expReal *  FastMath.cos(imaginary),
833                             expReal * FastMath.sin(imaginary));
834    }
835
836    /**
837     * Compute the
838     * <a href="http://mathworld.wolfram.com/NaturalLogarithm.html" TARGET="_top">
839     * natural logarithm</a> of this complex number.
840     * Implements the formula:
841     * <pre>
842     *  <code>
843     *   log(a + bi) = ln(|a + bi|) + arg(a + bi)i
844     *  </code>
845     * </pre>
846     * where ln on the right hand side is {@link FastMath#log},
847     * {@code |a + bi|} is the modulus, {@link Complex#abs},  and
848     * {@code arg(a + bi) = }{@link FastMath#atan2}(b, a).
849     * <br/>
850     * Returns {@link Complex#NaN} if either real or imaginary part of the
851     * input argument is {@code NaN}.
852     * <br/>
853     * Infinite (or critical) values in real or imaginary parts of the input may
854     * result in infinite or NaN values returned in parts of the result.
855     * <pre>
856     *  Examples:
857     *  <code>
858     *   log(1 &plusmn; INFINITY i) = INFINITY &plusmn; (&pi;/2)i
859     *   log(INFINITY + i) = INFINITY + 0i
860     *   log(-INFINITY + i) = INFINITY + &pi;i
861     *   log(INFINITY &plusmn; INFINITY i) = INFINITY &plusmn; (&pi;/4)i
862     *   log(-INFINITY &plusmn; INFINITY i) = INFINITY &plusmn; (3&pi;/4)i
863     *   log(0 + 0i) = -INFINITY + 0i
864     *  </code>
865     * </pre>
866     *
867     * @return the value <code>ln &nbsp; this</code>, the natural logarithm
868     * of {@code this}.
869     * @since 1.2
870     */
871    public Complex log() {
872        if (isNaN) {
873            return NaN;
874        }
875
876        return createComplex(FastMath.log(abs()),
877                             FastMath.atan2(imaginary, real));
878    }
879
880    /**
881     * Returns of value of this complex number raised to the power of {@code x}.
882     * Implements the formula:
883     * <pre>
884     *  <code>
885     *   y<sup>x</sup> = exp(x&middot;log(y))
886     *  </code>
887     * </pre>
888     * where {@code exp} and {@code log} are {@link #exp} and
889     * {@link #log}, respectively.
890     * <br/>
891     * Returns {@link Complex#NaN} if either real or imaginary part of the
892     * input argument is {@code NaN} or infinite, or if {@code y}
893     * equals {@link Complex#ZERO}.
894     *
895     * @param  x exponent to which this {@code Complex} is to be raised.
896     * @return <code> this<sup>{@code x}</sup></code>.
897     * @throws NullArgumentException if x is {@code null}.
898     * @since 1.2
899     */
900    public Complex pow(Complex x)
901        throws NullArgumentException {
902        MathUtils.checkNotNull(x);
903        return this.log().multiply(x).exp();
904    }
905
906    /**
907     * Returns of value of this complex number raised to the power of {@code x}.
908     *
909     * @param  x exponent to which this {@code Complex} is to be raised.
910     * @return <code>this<sup>x</sup></code>.
911     * @see #pow(Complex)
912     */
913     public Complex pow(double x) {
914        return this.log().multiply(x).exp();
915    }
916
917    /**
918     * Compute the
919     * <a href="http://mathworld.wolfram.com/Sine.html" TARGET="_top">
920     * sine</a>
921     * of this complex number.
922     * Implements the formula:
923     * <pre>
924     *  <code>
925     *   sin(a + bi) = sin(a)cosh(b) - cos(a)sinh(b)i
926     *  </code>
927     * </pre>
928     * where the (real) functions on the right-hand side are
929     * {@link FastMath#sin}, {@link FastMath#cos},
930     * {@link FastMath#cosh} and {@link FastMath#sinh}.
931     * <br/>
932     * Returns {@link Complex#NaN} if either real or imaginary part of the
933     * input argument is {@code NaN}.
934     * <br/>
935     * Infinite values in real or imaginary parts of the input may result in
936     * infinite or {@code NaN} values returned in parts of the result.
937     * <pre>
938     *  Examples:
939     *  <code>
940     *   sin(1 &plusmn; INFINITY i) = 1 &plusmn; INFINITY i
941     *   sin(&plusmn;INFINITY + i) = NaN + NaN i
942     *   sin(&plusmn;INFINITY &plusmn; INFINITY i) = NaN + NaN i
943     *  </code>
944     * </pre>
945     *
946     * @return the sine of this complex number.
947     * @since 1.2
948     */
949    public Complex sin() {
950        if (isNaN) {
951            return NaN;
952        }
953
954        return createComplex(FastMath.sin(real) * FastMath.cosh(imaginary),
955                             FastMath.cos(real) * FastMath.sinh(imaginary));
956    }
957
958    /**
959     * Compute the
960     * <a href="http://mathworld.wolfram.com/HyperbolicSine.html" TARGET="_top">
961     * hyperbolic sine</a> of this complex number.
962     * Implements the formula:
963     * <pre>
964     *  <code>
965     *   sinh(a + bi) = sinh(a)cos(b)) + cosh(a)sin(b)i
966     *  </code>
967     * </pre>
968     * where the (real) functions on the right-hand side are
969     * {@link FastMath#sin}, {@link FastMath#cos},
970     * {@link FastMath#cosh} and {@link FastMath#sinh}.
971     * <br/>
972     * Returns {@link Complex#NaN} if either real or imaginary part of the
973     * input argument is {@code NaN}.
974     * <br/>
975     * Infinite values in real or imaginary parts of the input may result in
976     * infinite or NaN values returned in parts of the result.
977     * <pre>
978     *  Examples:
979     *  <code>
980     *   sinh(1 &plusmn; INFINITY i) = NaN + NaN i
981     *   sinh(&plusmn;INFINITY + i) = &plusmn; INFINITY + INFINITY i
982     *   sinh(&plusmn;INFINITY &plusmn; INFINITY i) = NaN + NaN i
983     *  </code>
984     * </pre>
985     *
986     * @return the hyperbolic sine of {@code this}.
987     * @since 1.2
988     */
989    public Complex sinh() {
990        if (isNaN) {
991            return NaN;
992        }
993
994        return createComplex(FastMath.sinh(real) * FastMath.cos(imaginary),
995            FastMath.cosh(real) * FastMath.sin(imaginary));
996    }
997
998    /**
999     * Compute the
1000     * <a href="http://mathworld.wolfram.com/SquareRoot.html" TARGET="_top">
1001     * square root</a> of this complex number.
1002     * Implements the following algorithm to compute {@code sqrt(a + bi)}:
1003     * <ol><li>Let {@code t = sqrt((|a| + |a + bi|) / 2)}</li>
1004     * <li><pre>if {@code  a &#8805; 0} return {@code t + (b/2t)i}
1005     *  else return {@code |b|/2t + sign(b)t i }</pre></li>
1006     * </ol>
1007     * where <ul>
1008     * <li>{@code |a| = }{@link FastMath#abs}(a)</li>
1009     * <li>{@code |a + bi| = }{@link Complex#abs}(a + bi)</li>
1010     * <li>{@code sign(b) =  }{@link FastMath#copySign(double,double) copySign(1d, b)}
1011     * </ul>
1012     * <br/>
1013     * Returns {@link Complex#NaN} if either real or imaginary part of the
1014     * input argument is {@code NaN}.
1015     * <br/>
1016     * Infinite values in real or imaginary parts of the input may result in
1017     * infinite or NaN values returned in parts of the result.
1018     * <pre>
1019     *  Examples:
1020     *  <code>
1021     *   sqrt(1 &plusmn; INFINITY i) = INFINITY + NaN i
1022     *   sqrt(INFINITY + i) = INFINITY + 0i
1023     *   sqrt(-INFINITY + i) = 0 + INFINITY i
1024     *   sqrt(INFINITY &plusmn; INFINITY i) = INFINITY + NaN i
1025     *   sqrt(-INFINITY &plusmn; INFINITY i) = NaN &plusmn; INFINITY i
1026     *  </code>
1027     * </pre>
1028     *
1029     * @return the square root of {@code this}.
1030     * @since 1.2
1031     */
1032    public Complex sqrt() {
1033        if (isNaN) {
1034            return NaN;
1035        }
1036
1037        if (real == 0.0 && imaginary == 0.0) {
1038            return createComplex(0.0, 0.0);
1039        }
1040
1041        double t = FastMath.sqrt((FastMath.abs(real) + abs()) / 2.0);
1042        if (real >= 0.0) {
1043            return createComplex(t, imaginary / (2.0 * t));
1044        } else {
1045            return createComplex(FastMath.abs(imaginary) / (2.0 * t),
1046                                 FastMath.copySign(1d, imaginary) * t);
1047        }
1048    }
1049
1050    /**
1051     * Compute the
1052     * <a href="http://mathworld.wolfram.com/SquareRoot.html" TARGET="_top">
1053     * square root</a> of <code>1 - this<sup>2</sup></code> for this complex
1054     * number.
1055     * Computes the result directly as
1056     * {@code sqrt(ONE.subtract(z.multiply(z)))}.
1057     * <br/>
1058     * Returns {@link Complex#NaN} if either real or imaginary part of the
1059     * input argument is {@code NaN}.
1060     * <br/>
1061     * Infinite values in real or imaginary parts of the input may result in
1062     * infinite or NaN values returned in parts of the result.
1063     *
1064     * @return the square root of <code>1 - this<sup>2</sup></code>.
1065     * @since 1.2
1066     */
1067    public Complex sqrt1z() {
1068        return createComplex(1.0, 0.0).subtract(this.multiply(this)).sqrt();
1069    }
1070
1071    /**
1072     * Compute the
1073     * <a href="http://mathworld.wolfram.com/Tangent.html" TARGET="_top">
1074     * tangent</a> of this complex number.
1075     * Implements the formula:
1076     * <pre>
1077     *  <code>
1078     *   tan(a + bi) = sin(2a)/(cos(2a)+cosh(2b)) + [sinh(2b)/(cos(2a)+cosh(2b))]i
1079     *  </code>
1080     * </pre>
1081     * where the (real) functions on the right-hand side are
1082     * {@link FastMath#sin}, {@link FastMath#cos}, {@link FastMath#cosh} and
1083     * {@link FastMath#sinh}.
1084     * <br/>
1085     * Returns {@link Complex#NaN} if either real or imaginary part of the
1086     * input argument is {@code NaN}.
1087     * <br/>
1088     * Infinite (or critical) values in real or imaginary parts of the input may
1089     * result in infinite or NaN values returned in parts of the result.
1090     * <pre>
1091     *  Examples:
1092     *  <code>
1093     *   tan(a &plusmn; INFINITY i) = 0 &plusmn; i
1094     *   tan(&plusmn;INFINITY + bi) = NaN + NaN i
1095     *   tan(&plusmn;INFINITY &plusmn; INFINITY i) = NaN + NaN i
1096     *   tan(&plusmn;&pi;/2 + 0 i) = &plusmn;INFINITY + NaN i
1097     *  </code>
1098     * </pre>
1099     *
1100     * @return the tangent of {@code this}.
1101     * @since 1.2
1102     */
1103    public Complex tan() {
1104        if (isNaN || Double.isInfinite(real)) {
1105            return NaN;
1106        }
1107        if (imaginary > 20.0) {
1108            return createComplex(0.0, 1.0);
1109        }
1110        if (imaginary < -20.0) {
1111            return createComplex(0.0, -1.0);
1112        }
1113
1114        double real2 = 2.0 * real;
1115        double imaginary2 = 2.0 * imaginary;
1116        double d = FastMath.cos(real2) + FastMath.cosh(imaginary2);
1117
1118        return createComplex(FastMath.sin(real2) / d,
1119                             FastMath.sinh(imaginary2) / d);
1120    }
1121
1122    /**
1123     * Compute the
1124     * <a href="http://mathworld.wolfram.com/HyperbolicTangent.html" TARGET="_top">
1125     * hyperbolic tangent</a> of this complex number.
1126     * Implements the formula:
1127     * <pre>
1128     *  <code>
1129     *   tan(a + bi) = sinh(2a)/(cosh(2a)+cos(2b)) + [sin(2b)/(cosh(2a)+cos(2b))]i
1130     *  </code>
1131     * </pre>
1132     * where the (real) functions on the right-hand side are
1133     * {@link FastMath#sin}, {@link FastMath#cos}, {@link FastMath#cosh} and
1134     * {@link FastMath#sinh}.
1135     * <br/>
1136     * Returns {@link Complex#NaN} if either real or imaginary part of the
1137     * input argument is {@code NaN}.
1138     * <br/>
1139     * Infinite values in real or imaginary parts of the input may result in
1140     * infinite or NaN values returned in parts of the result.
1141     * <pre>
1142     *  Examples:
1143     *  <code>
1144     *   tanh(a &plusmn; INFINITY i) = NaN + NaN i
1145     *   tanh(&plusmn;INFINITY + bi) = &plusmn;1 + 0 i
1146     *   tanh(&plusmn;INFINITY &plusmn; INFINITY i) = NaN + NaN i
1147     *   tanh(0 + (&pi;/2)i) = NaN + INFINITY i
1148     *  </code>
1149     * </pre>
1150     *
1151     * @return the hyperbolic tangent of {@code this}.
1152     * @since 1.2
1153     */
1154    public Complex tanh() {
1155        if (isNaN || Double.isInfinite(imaginary)) {
1156            return NaN;
1157        }
1158        if (real > 20.0) {
1159            return createComplex(1.0, 0.0);
1160        }
1161        if (real < -20.0) {
1162            return createComplex(-1.0, 0.0);
1163        }
1164        double real2 = 2.0 * real;
1165        double imaginary2 = 2.0 * imaginary;
1166        double d = FastMath.cosh(real2) + FastMath.cos(imaginary2);
1167
1168        return createComplex(FastMath.sinh(real2) / d,
1169                             FastMath.sin(imaginary2) / d);
1170    }
1171
1172
1173
1174    /**
1175     * Compute the argument of this complex number.
1176     * The argument is the angle phi between the positive real axis and
1177     * the point representing this number in the complex plane.
1178     * The value returned is between -PI (not inclusive)
1179     * and PI (inclusive), with negative values returned for numbers with
1180     * negative imaginary parts.
1181     * <br/>
1182     * If either real or imaginary part (or both) is NaN, NaN is returned.
1183     * Infinite parts are handled as {@code Math.atan2} handles them,
1184     * essentially treating finite parts as zero in the presence of an
1185     * infinite coordinate and returning a multiple of pi/4 depending on
1186     * the signs of the infinite parts.
1187     * See the javadoc for {@code Math.atan2} for full details.
1188     *
1189     * @return the argument of {@code this}.
1190     */
1191    public double getArgument() {
1192        return FastMath.atan2(getImaginary(), getReal());
1193    }
1194
1195    /**
1196     * Computes the n-th roots of this complex number.
1197     * The nth roots are defined by the formula:
1198     * <pre>
1199     *  <code>
1200     *   z<sub>k</sub> = abs<sup>1/n</sup> (cos(phi + 2&pi;k/n) + i (sin(phi + 2&pi;k/n))
1201     *  </code>
1202     * </pre>
1203     * for <i>{@code k=0, 1, ..., n-1}</i>, where {@code abs} and {@code phi}
1204     * are respectively the {@link #abs() modulus} and
1205     * {@link #getArgument() argument} of this complex number.
1206     * <br/>
1207     * If one or both parts of this complex number is NaN, a list with just
1208     * one element, {@link #NaN} is returned.
1209     * if neither part is NaN, but at least one part is infinite, the result
1210     * is a one-element list containing {@link #INF}.
1211     *
1212     * @param n Degree of root.
1213     * @return a List<Complex> of all {@code n}-th roots of {@code this}.
1214     * @throws NotPositiveException if {@code n <= 0}.
1215     * @since 2.0
1216     */
1217    public List<Complex> nthRoot(int n) throws NotPositiveException {
1218
1219        if (n <= 0) {
1220            throw new NotPositiveException(LocalizedFormats.CANNOT_COMPUTE_NTH_ROOT_FOR_NEGATIVE_N,
1221                                           n);
1222        }
1223
1224        final List<Complex> result = new ArrayList<Complex>();
1225
1226        if (isNaN) {
1227            result.add(NaN);
1228            return result;
1229        }
1230        if (isInfinite()) {
1231            result.add(INF);
1232            return result;
1233        }
1234
1235        // nth root of abs -- faster / more accurate to use a solver here?
1236        final double nthRootOfAbs = FastMath.pow(abs(), 1.0 / n);
1237
1238        // Compute nth roots of complex number with k = 0, 1, ... n-1
1239        final double nthPhi = getArgument() / n;
1240        final double slice = 2 * FastMath.PI / n;
1241        double innerPart = nthPhi;
1242        for (int k = 0; k < n ; k++) {
1243            // inner part
1244            final double realPart = nthRootOfAbs *  FastMath.cos(innerPart);
1245            final double imaginaryPart = nthRootOfAbs *  FastMath.sin(innerPart);
1246            result.add(createComplex(realPart, imaginaryPart));
1247            innerPart += slice;
1248        }
1249
1250        return result;
1251    }
1252
1253    /**
1254     * Create a complex number given the real and imaginary parts.
1255     *
1256     * @param realPart Real part.
1257     * @param imaginaryPart Imaginary part.
1258     * @return a new complex number instance.
1259     * @since 1.2
1260     * @see #valueOf(double, double)
1261     */
1262    protected Complex createComplex(double realPart,
1263                                    double imaginaryPart) {
1264        return new Complex(realPart, imaginaryPart);
1265    }
1266
1267    /**
1268     * Create a complex number given the real and imaginary parts.
1269     *
1270     * @param realPart Real part.
1271     * @param imaginaryPart Imaginary part.
1272     * @return a Complex instance.
1273     */
1274    public static Complex valueOf(double realPart,
1275                                  double imaginaryPart) {
1276        if (Double.isNaN(realPart) ||
1277            Double.isNaN(imaginaryPart)) {
1278            return NaN;
1279        }
1280        return new Complex(realPart, imaginaryPart);
1281    }
1282
1283    /**
1284     * Create a complex number given only the real part.
1285     *
1286     * @param realPart Real part.
1287     * @return a Complex instance.
1288     */
1289    public static Complex valueOf(double realPart) {
1290        if (Double.isNaN(realPart)) {
1291            return NaN;
1292        }
1293        return new Complex(realPart);
1294    }
1295
1296    /**
1297     * Resolve the transient fields in a deserialized Complex Object.
1298     * Subclasses will need to override {@link #createComplex} to
1299     * deserialize properly.
1300     *
1301     * @return A Complex instance with all fields resolved.
1302     * @since 2.0
1303     */
1304    protected final Object readResolve() {
1305        return createComplex(real, imaginary);
1306    }
1307
1308    /** {@inheritDoc} */
1309    public ComplexField getField() {
1310        return ComplexField.getInstance();
1311    }
1312
1313    /** {@inheritDoc} */
1314    @Override
1315    public String toString() {
1316        return "(" + real + ", " + imaginary + ")";
1317    }
1318
1319}