Java Reference
In-Depth Information
Using Complex Numbers
Problem
You need to manipulate complex numbers, as is common in mathematical, scientific, or en-
gineering applications.
Solution
Java does not provide any explicit support for dealing with complex numbers. You could
keep track of the real and imaginary parts and do the computations yourself, but that is not a
very well-structured solution.
A better solution, of course, is to use a class that implements complex numbers. I provide
just such a class. First, an example of using it:
public
public class
ComplexDemo {
/** The program */
public
class ComplexDemo
public static
void main ( String [] args ) {
Complex c = new
static void
new Complex ( 3 , 5 );
Complex d = new
new Complex ( 2 , - 2 );
System . out . println ( c );
System . out . println ( c + ".getReal() = " + c . getReal ());
System . out . println ( c + " + " + d + " = " + c . add ( d ));
System . out . println ( c + " + " + d + " = " + Complex . add ( c , d ));
System . out . println ( c + " * " + d + " = " + c . multiply ( d ));
System . out . println ( Complex . divide ( c , d ));
}
}
Example 5-6 is the complete source for the Complex class and shouldn't require much ex-
planation.
To keep the API general, I provide—for each of add, subtract, and multiply—both a static
method that works on two complex objects and a nonstatic method that applies the operation
to the given object and one other object.
Example 5-6. Complex.java
public
public class
Complex {
/** The real part */
private
class Complex
private double
double r ;
Search WWH ::




Custom Search