Using Complex Numbers

Problem

You need to manipulate complex numbers, as is common in mathematical, scientific, or engineering 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:

// ComplexDemo.java 
Complex c = new Complex(3,  5); 
Complex d = new Complex(2, -2); 
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));

Example 5-4 is the complete source for the Complex class, and shouldn’t require much explanation. 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 non-static method that applies the operation to the given object and one other object.

Example 5-4. Complex.java

/** A class to represent Complex Numbers. A Complex object is * immutable once created; the add, subtract and multiply routines * return newly-created Complex objects containing the results. * */ public class Complex { /** The real part */ private double r; /** The imaginary part */ private double i; /** Construct a Complex */ ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.