8.8. Arithmetic with Complex Numbers
Problem
You need to perform arithmetic
with complex numbers. For example,
given the complex numbers A,
B, C, and
E and two equations shown in Figure 8-5, you need to find the real part of
F and the imaginary part of
D.

Figure 8-5. Expressions evaluated with the Complex object
Solution
Use Commons Math Complex and
ComplexMath classes to represent complex numbers
and perform arithmetic using complex numbers. Use the
ComplexFormat
class to print the real and imaginary parts of a complex number. The
following example demonstrates the use of the
Complex class to calculate D
and F from Figure 8-5 using
arbitrary values for A, B,
C, and E:
import org.apache.commons.math.complex.Complex;
import org.apache.commons.math.complex.ComplexFormat;
Complex a = new Complex(2, 3);
Complex b = new Complex(4, 5);
Complex c = new Complex(0.3, 2);
Complex e = new Complex(4, 4);
Complex sum = a.add( b );
Complex d = c.divide( sum );
Complex f = e.multiply( d.conjugate( ) );
System.out.println( "D is: " + ComplexFormat.formatComplex( d ) );
System.out.println( "F is: " + ComplexFormat.formatComplex( f ) );
double realF = f.getReal( );
double imD = d.getImaginary( );
double answer = realF / imD;
System.out.println( "Answer Re(F)/Im(D): " +
NumberFormat.getInstance( ).format( answer ) );The variables a, b,
c, and e are created using arbitrary values, and an intermediate ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access