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.
- Private Instance Variables:
private double realPart;
private double imagPart;
- 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. This is an initialization constructor.
Constructor Header: public Complex(double r, double i)
- 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. This is a default constructor.
Constructor Header: public Complex()
- 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.
Method Header: public boolean equals(Complex c)
- 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.
Method Header: public Complex add(Complex c)
- 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.
Method Header: public Complex multiply(Complex c)
- The class should have a toString()method that converts complex numbers into strings for the sake of
printing.
Method Header: public String toString()
Use the program ComplexTest.java, found in the class folder on the network, to test your Complex class.