Class ComplexNumber

java.lang.Object
java.lang.Number
io.github.sebian26.complex.ComplexNumber
All Implemented Interfaces:
Serializable, Comparable<ComplexNumber>

public class ComplexNumber extends Number implements Comparable<ComplexNumber>
Immutable complex number in double precision.

Design

The class keeps three levels of precision separate:
  1. Raw data. The real part, imaginary part, norm and angle store the exact results of floating-point calculations. Constructors and all arithmetic and analytic operations work on these raw values, with no implicit rounding.
  2. Equivalence classes. equals(Object), hashCode(), isZero(), isReal() and isImaginary() round the real and imaginary parts to 9 decimal digits. Numbers that round to the same pair are equal. Rounding always yields +0.0, never -0.0, so the sign of a negligible part does not affect equality.
  3. Representation. toString() and its overloads round to the display precision (default 3), which can never exceed the internal one.

Fixed parameters

Default format ComplexFormatEnum.ALG; internal precision 9 decimal digits; default display precision 3; default tolerance 1e-6.

Thread safety

All fields are final and there is no mutable static state, so instances can be shared freely between threads. Some operations return the same instance when the result is identical (see plus(ComplexNumber), times(ComplexNumber), conjugate()).

Overflow and underflow

Constructors reject non-finite values with an ArithmeticException. Arguments whose absolute value is at most Double.MIN_NORMAL are snapped to 0. Equality at 9 decimal digits becomes less meaningful for large magnitudes (from about 106 upwards), where a double no longer carries 9 significant decimals after the point.

Ordering

compareTo(ComplexNumber) returns 0 if and only if equals(Object) is true; otherwise it orders by norm, then angle, then real part, then imaginary part, all rounded to 9 decimal digits. The order is safe for TreeSet and TreeMap but has no canonical mathematical meaning.

Number

intValue(), longValue(), floatValue() and doubleValue() return the norm, not the real part.
See Also:
  • Field Details

    • ZERO

      public static final ComplexNumber ZERO
      The complex number 0.
    • ONE

      public static final ComplexNumber ONE
      The complex number 1.
    • I

      public static final ComplexNumber I
      The imaginary unit i = (0, 1).
  • Constructor Details

    • ComplexNumber

      public ComplexNumber(double x, double y, ComplexFormatEnum format)
      Constructs a complex number from two doubles interpreted according to a format.
      • ALG / MATR: x is the real part, y the imaginary part.
      • TRIG / EXP: x is the norm (must be ≥ 0), y the angle in radians. The stored angle is normalised to (-π, π] via atan2(sin(y), cos(y)); for norm 0 the angle is 0.
      Arguments whose absolute value is at most Double.MIN_NORMAL are snapped to 0.
      Parameters:
      x - real part (ALG/MATR) or norm (TRIG/EXP)
      y - imaginary part (ALG/MATR) or angle in radians (TRIG/EXP)
      format - how x and y are interpreted
      Throws:
      ArithmeticException - if an argument or their hypotenuse is not finite, or if x < 0 in TRIG/EXP format
      IllegalArgumentException - if the format is not recognised
    • ComplexNumber

      public ComplexNumber(double x, double y)
      Constructs the complex number x + iy.
      Parameters:
      x - real part
      y - imaginary part
      Throws:
      ArithmeticException - if the values are not finite
    • ComplexNumber

      public ComplexNumber(double x)
      Constructs the real number (x, 0).
      Parameters:
      x - real part
      Throws:
      ArithmeticException - if x is not finite
  • Method Details

    • getRealPart

      public double getRealPart()
      Returns the raw real part.
      Returns:
      the real part
    • getImaginaryPart

      public double getImaginaryPart()
      Returns the raw imaginary part.
      Returns:
      the imaginary part
    • getNorm

      public double getNorm()
      Returns the raw norm, always ≥ 0.
      Returns:
      the norm
    • getAngle

      public double getAngle()
      Returns the raw principal argument, in (-π, π].
      Returns:
      the angle in radians
    • intValue

      public int intValue()
      Specified by:
      intValue in class Number
      Returns:
      the norm truncated to an int (not the real part)
    • longValue

      public long longValue()
      Specified by:
      longValue in class Number
      Returns:
      the norm truncated to a long (not the real part)
    • floatValue

      public float floatValue()
      Specified by:
      floatValue in class Number
      Returns:
      the norm as a float (not the real part)
    • doubleValue

      public double doubleValue()
      Specified by:
      doubleValue in class Number
      Returns:
      the norm (not the real part); for example -3 gives 3
    • isZero

      public boolean isZero()
      Tests for zero at internal precision. Equivalent to equals(ZERO).
      Returns:
      true if both parts, rounded to 9 decimal digits, are zero
    • isReal

      public boolean isReal()
      Tests whether the number is real. Zero is real.
      Returns:
      true if the imaginary part, rounded to 9 decimal digits, is zero
    • isImaginary

      public boolean isImaginary()
      Tests whether the number is purely imaginary and non-zero.
      Returns:
      true if the real part, rounded to 9 decimal digits, is zero and the number is not zero
    • plus

      public ComplexNumber plus(ComplexNumber z)
      Returns this + z, or this itself if z is exactly 0.
      Parameters:
      z - the addend
      Returns:
      the sum
    • plus

      public ComplexNumber plus(double x)
      Returns this + x.
      Parameters:
      x - the real addend
      Returns:
      the sum
    • times

      public ComplexNumber times(ComplexNumber z)
      Returns this * z, or this itself if z is exactly 1.
      Parameters:
      z - the factor
      Returns:
      the product
    • times

      public ComplexNumber times(double x)
      Returns this * x, or this itself if x == 1.
      Parameters:
      x - the real factor
      Returns:
      the product
    • opposite

      public ComplexNumber opposite()
      Returns the opposite -this.
      Returns:
      the opposite
    • conjugate

      public ComplexNumber conjugate()
      Returns the complex conjugate re - i*im, or this itself if the imaginary part is exactly 0.
      Returns:
      the conjugate
    • inverse

      public ComplexNumber inverse()
      Returns 1 / this, computed as conjugate() / norm2.
      Returns:
      the inverse
      Throws:
      ArithmeticException - if this number is zero
    • minus

      public ComplexNumber minus(ComplexNumber z)
      Returns this - z.
      Parameters:
      z - the subtrahend
      Returns:
      the difference
    • minus

      public ComplexNumber minus(double x)
      Returns this - x.
      Parameters:
      x - the real subtrahend
      Returns:
      the difference
    • dividedBy

      public ComplexNumber dividedBy(ComplexNumber z)
      Returns this / z.
      Parameters:
      z - the divisor
      Returns:
      the quotient
      Throws:
      ArithmeticException - if z is zero
    • dividedBy

      public ComplexNumber dividedBy(double x)
      Returns this / x.
      Parameters:
      x - the real divisor
      Returns:
      the quotient
      Throws:
      ArithmeticException - if x is zero
    • raisedTo

      public ComplexNumber raisedTo(int n)
      Returns this^n.
      • n == 0: returns ONE (also for 0^0).
      • Real non-negative base: delegates to Math.pow(double, double).
      • Otherwise: De Moivre's formula norm^n (cos(nθ) + i sin(nθ)), valid for negative n as well, including Integer.MIN_VALUE.
      The error on nθ grows with |n|: for |n| around 109 the result can differ from the exact value by about 1e-7.
      Parameters:
      n - the integer exponent
      Returns:
      the power
      Throws:
      ArithmeticException - if the result is not finite (for example 0^(-1))
    • rootsOfOrder

      public List<ComplexNumber> rootsOfOrder(int n)
      Returns the n distinct n-th roots norm^(1/n) exp(i (angle/n + 2πk/n)), k = 0, ..., n-1. If this number is exactly zero and n > 0, the list contains the single element ZERO. If n <= 0, the list is empty.
      Parameters:
      n - the order of the roots
      Returns:
      the list of roots
    • exp

      public static ComplexNumber exp(ComplexNumber z)
      Returns e^z = e^re (cos(im) + i sin(im)), built directly in EXP form.
      Parameters:
      z - the exponent
      Returns:
      the exponential of z
      Throws:
      ArithmeticException - if the result is not finite
    • sinh

      public static ComplexNumber sinh(ComplexNumber z)
      Returns (e^z - e^(-z)) / 2. For real arguments uses Math.sinh(double).
      Parameters:
      z - the argument
      Returns:
      the hyperbolic sine of z
    • cosh

      public static ComplexNumber cosh(ComplexNumber z)
      Returns (e^z + e^(-z)) / 2. For real arguments uses Math.cosh(double).
      Parameters:
      z - the argument
      Returns:
      the hyperbolic cosine of z
    • sin

      public static ComplexNumber sin(ComplexNumber z)
      Returns sinh(iz) / i. For real arguments uses Math.sin(double).
      Parameters:
      z - the argument
      Returns:
      the sine of z
    • cos

      public static ComplexNumber cos(ComplexNumber z)
      Returns cosh(iz). For real arguments uses Math.cos(double).
      Parameters:
      z - the argument
      Returns:
      the cosine of z
    • tan

      public static ComplexNumber tan(ComplexNumber z)
      Returns sin(z) / cos(z). Near the poles (e.g. tan(π/2)) the result is very large but finite, since the denominator is never exactly zero in double precision.
      Parameters:
      z - the argument
      Returns:
      the tangent of z
    • tanh

      public static ComplexNumber tanh(ComplexNumber z)
      Returns sinh(z) / cosh(z).
      Parameters:
      z - the argument
      Returns:
      the hyperbolic tangent of z
    • asin

      public static ComplexNumber asin(ComplexNumber z)
      Returns the principal arc sine i Ln(sqrt(1 - z2) - iz). asin(1) = π/2 and asin(-1) = -π/2. On the branch cuts (real z with |z| > 1): z > 1 gives π/2 - i ln(z + sqrt(z2 - 1)), z < -1 gives -π/2 + i ln(|z| + sqrt(z2 - 1)). For z > 1 this is the complex conjugate of the C99 convention.
      Parameters:
      z - the argument
      Returns:
      the principal arc sine of z
    • acos

      public static ComplexNumber acos(ComplexNumber z)
      Returns the principal arc cosine π/2 - asin(z).
      Parameters:
      z - the argument
      Returns:
      the principal arc cosine of z
    • atan

      public static ComplexNumber atan(ComplexNumber z)
      Returns the principal arc tangent (-i/2) Ln((i - z) / (i + z)).
      Parameters:
      z - the argument
      Returns:
      the principal arc tangent of z
      Throws:
      ArithmeticException - for z = ±i (singularities)
    • principalLn

      public static ComplexNumber principalLn(ComplexNumber z)
      Returns the principal logarithm Ln(z) = ln|z| + i arg(z), with arg(z) in (-π, π].
      Parameters:
      z - the argument
      Returns:
      the principal logarithm of z
      Throws:
      ArithmeticException - if z is zero
    • raisedTo

      public ComplexNumber raisedTo(ComplexNumber z)
      Returns this^z on the principal branch, exp(z Ln(this)). Returns ONE if z is exactly 0; delegates to Math.pow(double, double) if this number is real and non-negative and z is real.
      Parameters:
      z - the complex exponent
      Returns:
      the power
      Throws:
      ArithmeticException - if the result is not finite, or if this number is zero and z is not real
    • raisedTo

      public ComplexNumber raisedTo(double x)
      Returns this^x on the principal branch, exp(x Ln(this)). Returns ONE if x == 0; delegates to Math.pow(double, double) if this number is real and non-negative.
      Parameters:
      x - the real exponent
      Returns:
      the power
      Throws:
      ArithmeticException - if the result is not finite
    • pow

      public static ComplexNumber pow(double x, ComplexNumber z)
      Returns x^z. Equivalent to new ComplexNumber(x).raisedTo(z).
      Parameters:
      x - the real base
      z - the complex exponent
      Returns:
      the power
      Throws:
      ArithmeticException - if the result is not finite
    • compareTo

      public int compareTo(ComplexNumber z)
      Compares by norm, then angle, then real part, then imaginary part, all rounded to 9 decimal digits. Returns 0 if and only if equals(Object) is true.
      Specified by:
      compareTo in interface Comparable<ComplexNumber>
      Parameters:
      z - the number to compare with
      Returns:
      a negative, zero or positive integer
    • hashCode

      public int hashCode()
      Consistent with equals(Object): computed from the real and imaginary parts rounded to 9 decimal digits.
      Overrides:
      hashCode in class Object
      Returns:
      the hash code
    • equals

      public boolean equals(Object o)
      Two complex numbers are equal if their real and imaginary parts coincide when rounded to 9 decimal digits. In particular, every number with both parts below 5e-10 in absolute value equals ZERO.
      Overrides:
      equals in class Object
      Parameters:
      o - the object to compare with
      Returns:
      true if o is an equal ComplexNumber; false for null and other classes
    • isCloseTo

      public boolean isCloseTo(ComplexNumber z, double tolerance)
      Tests whether |this - z| < tolerance.
      Parameters:
      z - the number to compare with; null gives false
      tolerance - the maximum distance, exclusive
      Returns:
      true if the distance is strictly less than tolerance
      Throws:
      IllegalArgumentException - if tolerance is not finite or is ≤ 1e-9
    • isCloseTo

      public boolean isCloseTo(ComplexNumber z)
      Equivalent to isCloseTo(z, 1e-6).
      Parameters:
      z - the number to compare with; null gives false
      Returns:
      true if the distance is strictly less than 1e-6
    • toString

      public String toString()
      Returns the number in ALG format with 3 decimal digits.
      Overrides:
      toString in class Object
      Returns:
      the string representation
      See Also:
    • toString

      public String toString(ComplexFormatEnum format)
      Returns the number in the given format with 3 decimal digits.
      Parameters:
      format - the output format
      Returns:
      the string representation
      See Also:
    • toString

      public String toString(int precision)
      Returns the number in ALG format with the given precision.
      Parameters:
      precision - the number of decimal digits, in [0, 9]
      Returns:
      the string representation
      Throws:
      IllegalArgumentException - if precision is outside [0, 9]
      See Also:
    • toString

      public String toString(ComplexFormatEnum format, int precision)
      Returns the number in the given format and precision.
      • ALG: "a + bi" or "a - bi"
      • TRIG: "r(cos(θ) + isin(θ))"
      • EXP: "rexp(θi)"
      • MATR: the 2x2 real matrix [a -b; b a], column width 12, independent of the default locale
      Reduced forms are decided on the values rounded to the display precision: if both parts round to 0 the result is "0" (in every format); otherwise, except in MATR, a zero imaginary part gives "a" and a zero real part gives "bi". Values are printed with Double.toString(double), so very small or very large values use scientific notation (e.g. "1.0E-5").
      Parameters:
      format - the output format
      precision - the number of decimal digits, in [0, 9] ([0, 6] for MATR)
      Returns:
      the string representation
      Throws:
      IllegalArgumentException - if precision is out of range
    • complexListToString

      public static String complexListToString(List<ComplexNumber> list)
      Formats a list with one number per line, using toString().
      Parameters:
      list - the numbers to format
      Returns:
      the formatted list, or "" for a null or empty list
    • valueOf

      public static ComplexNumber valueOf(String str)
      Parses a string into a ComplexNumber. Whitespace is ignored.

      Accepted forms:

      • real: "3.14", "-2", "1e3"
      • purely imaginary: "i", "-i", "+i", "2.5i"
      • algebraic: "3+2i", "-1-4i", "1e3+2.5e-2i"
      • exponential: "2exp(1.5i)", "exp(-0.5i)", "+exp(1i)"
      In scientific notation the sign of the exponent is distinguished from the sign between the two parts. A negative coefficient before exp is rejected, because the norm cannot be negative. The output of toString() in ALG and EXP format can be read back; TRIG and MATR output cannot.
      Parameters:
      str - the string to parse
      Returns:
      the parsed number
      Throws:
      NumberFormatException - if str is null or blank, does not match a supported form, or gives a non-finite value