Class ComplexNumber
java.lang.Object
java.lang.Number
io.github.sebian26.complex.ComplexNumber
- All Implemented Interfaces:
Serializable, Comparable<ComplexNumber>
Immutable complex number in double precision.
Design
The class keeps three levels of precision separate:- 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.
- Equivalence classes.
equals(Object),hashCode(),isZero(),isReal()andisImaginary()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. - Representation.
toString()and its overloads round to the display precision (default 3), which can never exceed the internal one.
Fixed parameters
Default formatComplexFormatEnum.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 (seeplus(ComplexNumber),
times(ComplexNumber), conjugate()).
Overflow and underflow
Constructors reject non-finite values with anArithmeticException.
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 Summary
FieldsModifier and TypeFieldDescriptionstatic final ComplexNumberThe imaginary unit i = (0, 1).static final ComplexNumberThe complex number 1.static final ComplexNumberThe complex number 0. -
Constructor Summary
ConstructorsConstructorDescriptionComplexNumber(double x) Constructs the real number(x, 0).ComplexNumber(double x, double y) Constructs the complex numberx + iy.ComplexNumber(double x, double y, ComplexFormatEnum format) Constructs a complex number from two doubles interpreted according to a format. -
Method Summary
Modifier and TypeMethodDescriptionstatic ComplexNumberReturns the principal arc cosineπ/2 - asin(z).static ComplexNumberReturns the principal arc sinei Ln(sqrt(1 - z2) - iz).static ComplexNumberReturns the principal arc tangent(-i/2) Ln((i - z) / (i + z)).intCompares by norm, then angle, then real part, then imaginary part, all rounded to 9 decimal digits.static StringcomplexListToString(List<ComplexNumber> list) Formats a list with one number per line, usingtoString().Returns the complex conjugatere - i*im, orthisitself if the imaginary part is exactly 0.static ComplexNumbercos(ComplexNumber z) Returnscosh(iz).static ComplexNumberReturns(e^z + e^(-z)) / 2.dividedBy(double x) Returnsthis / x.Returnsthis / z.doublebooleanTwo complex numbers are equal if their real and imaginary parts coincide when rounded to 9 decimal digits.static ComplexNumberexp(ComplexNumber z) Returnse^z = e^re (cos(im) + i sin(im)), built directly in EXP form.floatdoublegetAngle()Returns the raw principal argument, in (-π, π].doubleReturns the raw imaginary part.doublegetNorm()Returns the raw norm, always ≥ 0.doubleReturns the raw real part.inthashCode()Consistent withequals(Object): computed from the real and imaginary parts rounded to 9 decimal digits.intintValue()inverse()Returns1 / this, computed asconjugate() / norm2.booleanEquivalent toisCloseTo(z, 1e-6).booleanisCloseTo(ComplexNumber z, double tolerance) Tests whether|this - z| < tolerance.booleanTests whether the number is purely imaginary and non-zero.booleanisReal()Tests whether the number is real.booleanisZero()Tests for zero at internal precision.longminus(double x) Returnsthis - x.Returnsthis - z.opposite()Returns the opposite-this.plus(double x) Returnsthis + x.Returnsthis + z, orthisitself ifzis exactly 0.static ComplexNumberpow(double x, ComplexNumber z) Returnsx^z.static ComplexNumberReturns the principal logarithmLn(z) = ln|z| + i arg(z), witharg(z)in (-π, π].raisedTo(double x) Returnsthis^xon the principal branch,exp(x Ln(this)).raisedTo(int n) Returnsthis^n.Returnsthis^zon the principal branch,exp(z Ln(this)).rootsOfOrder(int n) Returns thendistinct n-th rootsnorm^(1/n) exp(i (angle/n + 2πk/n)),k = 0, ..., n-1.static ComplexNumbersin(ComplexNumber z) Returnssinh(iz) / i.static ComplexNumberReturns(e^z - e^(-z)) / 2.static ComplexNumbertan(ComplexNumber z) Returnssin(z) / cos(z).static ComplexNumberReturnssinh(z) / cosh(z).times(double x) Returnsthis * x, orthisitself ifx == 1.Returnsthis * z, orthisitself ifzis exactly 1.toString()Returns the number in ALG format with 3 decimal digits.toString(int precision) Returns the number in ALG format with the given precision.toString(ComplexFormatEnum format) Returns the number in the given format with 3 decimal digits.toString(ComplexFormatEnum format, int precision) Returns the number in the given format and precision.static ComplexNumberParses a string into a ComplexNumber.Methods inherited from class Number
byteValue, shortValue
-
Field Details
-
ZERO
The complex number 0. -
ONE
The complex number 1. -
I
The imaginary unit i = (0, 1).
-
-
Constructor Details
-
ComplexNumber
Constructs a complex number from two doubles interpreted according to a format.ALG/MATR:xis the real part,ythe imaginary part.TRIG/EXP:xis the norm (must be ≥ 0),ythe angle in radians. The stored angle is normalised to (-π, π] viaatan2(sin(y), cos(y)); for norm 0 the angle is 0.
Double.MIN_NORMALare 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- howxandyare interpreted- Throws:
ArithmeticException- if an argument or their hypotenuse is not finite, or ifx < 0in TRIG/EXP formatIllegalArgumentException- if the format is not recognised
-
ComplexNumber
public ComplexNumber(double x, double y) Constructs the complex numberx + iy.- Parameters:
x- real party- 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- ifxis 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
-
longValue
-
floatValue
public float floatValue()- Specified by:
floatValuein classNumber- Returns:
- the norm as a float (not the real part)
-
doubleValue
public double doubleValue()- Specified by:
doubleValuein classNumber- Returns:
- the norm (not the real part); for example -3 gives 3
-
isZero
public boolean isZero()Tests for zero at internal precision. Equivalent toequals(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
Returnsthis + z, orthisitself ifzis exactly 0.- Parameters:
z- the addend- Returns:
- the sum
-
plus
Returnsthis + x.- Parameters:
x- the real addend- Returns:
- the sum
-
times
Returnsthis * z, orthisitself ifzis exactly 1.- Parameters:
z- the factor- Returns:
- the product
-
times
Returnsthis * x, orthisitself ifx == 1.- Parameters:
x- the real factor- Returns:
- the product
-
opposite
-
conjugate
Returns the complex conjugatere - i*im, orthisitself if the imaginary part is exactly 0.- Returns:
- the conjugate
-
inverse
Returns1 / this, computed asconjugate() / norm2.- Returns:
- the inverse
- Throws:
ArithmeticException- if this number is zero
-
minus
Returnsthis - z.- Parameters:
z- the subtrahend- Returns:
- the difference
-
minus
Returnsthis - x.- Parameters:
x- the real subtrahend- Returns:
- the difference
-
dividedBy
Returnsthis / z.- Parameters:
z- the divisor- Returns:
- the quotient
- Throws:
ArithmeticException- ifzis zero
-
dividedBy
Returnsthis / x.- Parameters:
x- the real divisor- Returns:
- the quotient
- Throws:
ArithmeticException- ifxis zero
-
raisedTo
Returnsthis^n.n == 0: returnsONE(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 negativenas well, includingInteger.MIN_VALUE.
nθgrows with|n|: for|n|around 109 the result can differ from the exact value by about1e-7.- Parameters:
n- the integer exponent- Returns:
- the power
- Throws:
ArithmeticException- if the result is not finite (for example 0^(-1))
-
rootsOfOrder
Returns thendistinct n-th rootsnorm^(1/n) exp(i (angle/n + 2πk/n)),k = 0, ..., n-1. If this number is exactly zero andn > 0, the list contains the single elementZERO. Ifn <= 0, the list is empty.- Parameters:
n- the order of the roots- Returns:
- the list of roots
-
exp
Returnse^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
Returns(e^z - e^(-z)) / 2. For real arguments usesMath.sinh(double).- Parameters:
z- the argument- Returns:
- the hyperbolic sine of
z
-
cosh
Returns(e^z + e^(-z)) / 2. For real arguments usesMath.cosh(double).- Parameters:
z- the argument- Returns:
- the hyperbolic cosine of
z
-
sin
Returnssinh(iz) / i. For real arguments usesMath.sin(double).- Parameters:
z- the argument- Returns:
- the sine of
z
-
cos
Returnscosh(iz). For real arguments usesMath.cos(double).- Parameters:
z- the argument- Returns:
- the cosine of
z
-
tan
Returnssin(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
Returnssinh(z) / cosh(z).- Parameters:
z- the argument- Returns:
- the hyperbolic tangent of
z
-
asin
Returns the principal arc sinei Ln(sqrt(1 - z2) - iz).asin(1) = π/2andasin(-1) = -π/2. On the branch cuts (realzwith|z| > 1):z > 1givesπ/2 - i ln(z + sqrt(z2 - 1)),z < -1gives-π/2 + i ln(|z| + sqrt(z2 - 1)). Forz > 1this is the complex conjugate of the C99 convention.- Parameters:
z- the argument- Returns:
- the principal arc sine of
z
-
acos
Returns the principal arc cosineπ/2 - asin(z).- Parameters:
z- the argument- Returns:
- the principal arc cosine of
z
-
atan
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- forz = ±i(singularities)
-
principalLn
Returns the principal logarithmLn(z) = ln|z| + i arg(z), witharg(z)in (-π, π].- Parameters:
z- the argument- Returns:
- the principal logarithm of
z - Throws:
ArithmeticException- ifzis zero
-
raisedTo
Returnsthis^zon the principal branch,exp(z Ln(this)). ReturnsONEifzis exactly 0; delegates toMath.pow(double, double)if this number is real and non-negative andzis real.- Parameters:
z- the complex exponent- Returns:
- the power
- Throws:
ArithmeticException- if the result is not finite, or if this number is zero andzis not real
-
raisedTo
Returnsthis^xon the principal branch,exp(x Ln(this)). ReturnsONEifx == 0; delegates toMath.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
Returnsx^z. Equivalent tonew ComplexNumber(x).raisedTo(z).- Parameters:
x- the real basez- the complex exponent- Returns:
- the power
- Throws:
ArithmeticException- if the result is not finite
-
compareTo
Compares by norm, then angle, then real part, then imaginary part, all rounded to 9 decimal digits. Returns 0 if and only ifequals(Object)is true.- Specified by:
compareToin interfaceComparable<ComplexNumber>- Parameters:
z- the number to compare with- Returns:
- a negative, zero or positive integer
-
hashCode
public int hashCode()Consistent withequals(Object): computed from the real and imaginary parts rounded to 9 decimal digits. -
equals
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 below5e-10in absolute value equalsZERO. -
isCloseTo
Tests whether|this - z| < tolerance.- Parameters:
z- the number to compare with;nullgives falsetolerance- the maximum distance, exclusive- Returns:
- true if the distance is strictly less than
tolerance - Throws:
IllegalArgumentException- iftoleranceis not finite or is ≤ 1e-9
-
isCloseTo
Equivalent toisCloseTo(z, 1e-6).- Parameters:
z- the number to compare with;nullgives false- Returns:
- true if the distance is strictly less than
1e-6
-
toString
-
toString
Returns the number in the given format with 3 decimal digits.- Parameters:
format- the output format- Returns:
- the string representation
- See Also:
-
toString
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- ifprecisionis outside [0, 9]- See Also:
-
toString
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
"0"(in every format); otherwise, except in MATR, a zero imaginary part gives"a"and a zero real part gives"bi". Values are printed withDouble.toString(double), so very small or very large values use scientific notation (e.g."1.0E-5").- Parameters:
format- the output formatprecision- the number of decimal digits, in [0, 9] ([0, 6] for MATR)- Returns:
- the string representation
- Throws:
IllegalArgumentException- ifprecisionis out of range
- ALG:
-
complexListToString
Formats a list with one number per line, usingtoString().- Parameters:
list- the numbers to format- Returns:
- the formatted list, or
""for a null or empty list
-
valueOf
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)"
expis rejected, because the norm cannot be negative. The output oftoString()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- ifstris null or blank, does not match a supported form, or gives a non-finite value
- real:
-