Implementing
Complex Numbers with Class
Java
has a number of built-in types such as int, char, boolean, float, and double,
among others. Scientists and engineers often like to work with complex numbers,
but complex numbers are not a built-in type in Java. Therefore, your task is to
implement a complex number class. The class should be implemented in a file
named Complex.java.
Recall
that a complex number is of the form a + bi where a
and b are real numbers and i is an
imaginary number. Addition of two complex numbers is defined by (a + bi) +
(c + di) = (a+c) + (b+d)i.
Similarly, to multiply two complex numbers, we simply compute (a + bi) * (c
+ di) = ac + adi + bci + bdi2 = (ac - bd)
+ (ad + bc) i since i2 is -1 by definition.
In
your implementation, the numbers a and b
in the complex number a + bi should be represented by doubles. Below are the public methods (functions) that your Complex class should contain. Be sure to use
exactly these names and the specified kinds of arguments and return values. You
may use any additional private methods that you like in order to build your public
methods.
- The class should have a
constructor that takes two double arguments and sets the
real and imaginary components of the complex number to these values.
- The class should have a
second constructor that takes no arguments and simply sets the real and
imaginary components of the complex number to both be
0.0.
- The class should have a
method called equals
that takes a Complex
argument and determines if the two Complex numbers (this
one and the argument) are equal. The method returns a boolean
which is true
if the numbers are equal and false otherwise.
- The class should have a
method called add
that takes a Complex
argument and returns the sum of this Complex
number and the argument. Thus, the return value is a Complex
number itself and neither of the summands has their values changed in any
way.
- The class should have a
method called multiply
that takes a Complex
argument and returns the product of this Complex
number and the argument. Thus the return value is a Complex
number itself and neither of the multiplicands has their values changed in
any way.
- The class should have a toString()
method that converts complex numbers into strings for the sake of
printing.
As always, write a program to test your Complex class.