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