Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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 */ ...
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.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata