Share on Google+Share on Google+

Implement Complex Number Class

Advertisement
Here we are going to implement Complex Number class and perform operations on it.

Implement Complex Number Class

You all are aware of Complex Numbers. These numbers consists of two parts,real and imaginary which can be written in the form of a+ib, where a and b are real numbers and i is the imaginary unit with the property i 2 =−1. You can extend them by adding extra numbers. Here we are going to implement Complex Number class and perform operations on it.

Here is the code:

public class ComplexNumber {
	private int a;
	private int b;

	public ComplexNumber() {
	}

	public ComplexNumber(int a, int b) {
		this.a = a;
		this.b = b;
	}

	public String getComplexValue() {
		if (this.b < 0) {
			return a + "" + b + "i";
		} else {
			return a + "+" + b + "i";
		}
	}

	public static String addition(ComplexNumber num1, ComplexNumber num2) {
		int a1 = num1.a + num2.a;
		int b1 = num1.b + num2.b;
		if (b1 < 0) {
			return a1 + "" + b1 + "i";
		} else {
			return a1 + "+" + b1 + "i";
		}
	}

	public static String substraction(ComplexNumber num1, ComplexNumber num2) {
		int a1 = num1.a - num2.a;
		int b1 = num1.b - num2.b;
		if (b1 < 0) {
			return a1 + "" + b1 + "i";
		} else {
			return a1 + "+" + b1 + "i";
		}
	}

	public static String multiplication(ComplexNumber num1, ComplexNumber num2) {
		int a1 = num1.a * num2.a;
		int b1 = num1.b * num2.b;
		int vi1 = num1.a * num2.b;
		int vi2 = num2.a * num1.b;
		int vi;
		vi = vi1 + vi2;
		if (vi < 0) {
			return a1 - b1 + "" + vi + "i";
		} else {
			return a1 - b1 + "+" + vi + "i";
		}
	}

	public static void main(String args[]) {
		ComplexNumber com1 = new ComplexNumber(-2, -3);
		ComplexNumber com2 = new ComplexNumber(-4, -5);
		System.out.println(com1.getComplexValue());
		System.out.println(com2.getComplexValue());
		System.out.println("Addition of Complex Numbers is :"
				+ ComplexNumber.addition(com1, com2));
		System.out.println("Subtraction of Complex Numbers is :"
				+ ComplexNumber.substraction(com1, com2));
		System.out.println("Multiplication of Complex Numbers is :"
				+ ComplexNumber.multiplication(com1, com2));
	}
}

Output:

-2-3i
-4-5i
Addition of Complex Numbers is: -6-8i
Subtraction of Complex Numbers is: 2+2i
Multiplication of Complex Numbers is: -7 + 22i

Advertisements

Posted on: July 9, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.