In: Computer Science
***JAVA PLEASE*** All correct and complete responses will receive a thumbs up and positive comment! Thank you!!
Create a simple class that emulates some mathematical functions in relation to complex numbers. A complex number is a number of the form a + bi, where a is a real number and bi is an imaginary number. Create a class Complex having two private data members real and imag of type double. The class has two constructors, one default (no parameters) and one whose parameters initialize the instance variables. It also need the following member functions, all of which are public:
**** ALSO Write a driver program to test all of the above functions***
Hints: For complex numbers:
Addition: add the real and imaginary components separately:
(7 + 4i) + (23 – 12i) = 30 – 8i
Subtraction: subtract the real and imaginary components separately:
(7 + 4i) - (23 – 12i) = -16 + 16i
Multiplication: More complicated
Code
Complex.java
public class Complex
{
private double real,imag;
public Complex()
{
this.real=0;
this.imag=0;
}
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImag() {
return imag;
}
public void setImag(double imag) {
this.imag = imag;
}
public void addComplex(Complex z)
{
real=real+z.real;
imag=imag+z.imag;
}
public void subtractComplex (Complex z)
{
real=real-z.real;
imag=imag-z.imag;
}
public void multiplyComplex (Complex z)
{
real=(real*z.real)-(imag*z.imag);
imag=(real*z.imag)+(z.real*imag);
}
public void print ()
{
if (imag==0) {
System.out.print("( "+imag);
}
else if (imag>0)
{
System.out.print("("+real+"+"+imag+"i)");
}
else
System.out.print("("+real+" - "+(-imag)+"i)");
}
}
Driver file
TestComple.java
public class TestComolex
{
public static void main(String[] args)
{
Complex c1=new Complex(7,4);
Complex c2=new Complex(23,-12);
c1.print();
System.out.print(" + ");
c2.print();
c1.addComplex(c2);
System.out.print(" = ");
c1.print();
System.out.println("");
}
}
outputs
If you have any query regarding the code please ask me in the
comment i am here for help you. Please do not direct thumbs down
just ask if you have any query. And if you like my work then please
appreciates with up vote. Thank You.