1. Introduction
In this tutorial, we’ll examine arithmetic operations on complex numbers. Specifically, we’ll explore how to perform addition, subtraction, multiplication, and division of two complex numbers in Java.
2. What is a Complex Number?
Complex numbers are expressed using a combination of real and imaginary parts. They are generally denoted as a+bi, where a and b are real numbers and i represents the imaginary unit equivalent to the square root of -1. In formal mathematical notation, a is the real part of the complex number, and the term bi is the imaginary component. Complex numbers, although initially confusing for newcomers, play a crucial role in various practical applications, such as physics and mathematics, including fields like quantum mechanics, signal processing, and economics.
Like real numbers, we can perform arithmetic operations such as addition, subtraction, multiplication, and division. Performing arithmetic operations on complex numbers introduces complexities due to the combination of real and imaginary parts. However, specific formulas exist for each of these operations, which streamline them and ensure accurate results.
3. Set Up
We can set up the required foundational code before implementing the arithmetic operations on complex numbers. Let’s start with defining a class for representing complex numbers:
public record ComplexNumber(double real, double imaginary) {
public static ComplexNumber fromString(String complexNumberStr) {
Pattern pattern = Pattern.compile("(-?\\d*\\.?\\d+)?(?:([+-]?\\d*\\.?\\d+)i)?");
Matcher matcher = pattern.matcher(complexNumberStr.replaceAll("\\s", ""));
if (matcher.matches()) {
// Extract real and imaginary parts
String realPartStr = matcher.group(1);
String imaginaryPartStr = matcher.group(2);
// Parse real part (if present)
double real = (realPartStr != null) ? Double.parseDouble(realPartStr) : 0;
// Parse imaginary part (if present)
double imaginary = (imaginaryPartStr != null) ? Double.parseDouble(imaginaryPartStr) : 0;
return new ComplexNumber(real, imaginary);
} else {
throw new IllegalArgumentException("Invalid complex number format(" + complexNumberStr + "), supported format is `a+bi`");
}
}
public String toString() {
return real + "+" + imaginary + "i";
}
The above class defines the real and imaginary parts of a complex number. We utilized the record keyword to define the class to represent the complex number. Moreover, we defined the toString() method to return the complex number in the typical format of a+bi.
Additionally, the fromString() method is overridden to parse a string representation of a complex number into the ComplexNumber record. We utilized regular expression groups to extract the real and imaginary parts from the string.
In the subsequent sections, we can enhance this record by adding methods to perform various arithmetic operations.
4. Addition of Two Complex Numbers
Now that the basic setup is ready, let’s implement the method for adding two complex numbers. Complex number addition involves adding the real and imaginary parts of two numbers separately to obtain the resultant number. To provide a clearer understanding, let’s establish the addition formula. Let’s look at the formula for addition of two complex numbers:
Let’s translate this formula into Java code and incorporate it into the ComplexNumber record:
public ComplexNumber add(ComplexNumber that) {
return new ComplexNumber(real + that.real, imaginary + that.imaginary);
}
We can directly access the real and imaginary components from the record and combine them with the given complex number within the method.
5. Subtraction of Two Complex Numbers
Subtracting two complex numbers involves subtracting their real and imaginary parts separately. When subtracting complex numbers a+bi and c+di, we subtract the real parts (a and c) and the imaginary parts (b and d) separately, resulting in a new complex number with the real part as the difference of the original real parts and the imaginary part as the difference of the original imaginary parts. Here is the formula for the subtraction operation:
Let’s implement the method for subtraction in Java:
public ComplexNumber subtract(ComplexNumber that) {
return new ComplexNumber(real - that.real, imaginary - that.imaginary);
}
This implements the subtraction using the formula (a-c)+(b-d)i.
6. Multiplication of Two Complex Numbers
Unlike addition and subtraction, multiplication of two complex numbers is not so straightforward. Let’s look at the formula for the multiplication:
We can translate this formula into Java code and add the method to multiply two complex numbers:
public ComplexNumber multiply(ComplexNumber that) {
double newReal = this.real * that.real - this.imaginary * that.imaginary;
double newImaginary = this.real * that.imaginary + this.imaginary * that.real;
return new ComplexNumber(newReal, newImaginary);
}
The above method implements the algorithm for the complex number multiplication.
7. Division of Two Complex Numbers
Division of two complex numbers is even more complicated than multiplication. It involves a more complex formula:
Let’s translate this into a Java method:
public ComplexNumber divide(ComplexNumber that) {
if (that.real == 0 && that.imaginary == 0) {
throw new ArithmeticException("Division by 0 is not allowed!");
}
double c2d2 = Math.pow(that.real, 2) + Math.pow(that.imaginary, 2);
double newReal = (this.real * that.real + this.imaginary * that.imaginary) / c2d2;
double newImaginary = (this.imaginary * that.real - this.real * that.imaginary) / c2d2;
return new ComplexNumber(newReal, newImaginary);
}
The above method effectively divides two complex numbers. It incorporates error handling to prevent division by zero and provides a clear error message in such cases.
8. Testing the Implementation
Now that we have implemented the arithmetic operations on two complex numbers, let’s write test cases for each method. Complex numbers can have various forms, including those with only a real part, only an imaginary part, or both. To guarantee a robust implementation, we must thoroughly test our implementations across all these scenarios. For comprehensive coverage, we can utilize the parameterized tests from JUnit to test different inputs.
To maintain conciseness within this article, we will focus on a single test case demonstrating complex number division:
@ParameterizedTest(name = "Dividing {0} and {1}")
@CsvSource({
"3+2i, 1+7i, 0.34-0.38i",
"2, 4, 0.5",
"2, 4i, 0-0.5i",
"1+1i, 1+1i, 1",
"3 + 2i, 1 + 7i, 0.34-0.38i",
"0+5i, 3+0i, 0+1.6666666666666667i",
"0+0i, -2+0i, 0+0i",
"-3+2i, 1-7i, -0.34-0.38i",
"2+4i, 1, 2+4i"
})
public void givenTwoComplexNumbers_divideThemAndGetResult(String complexStr1, String complexStr2, String expectedStr) {
ComplexNumber complex1 = ComplexNumber.fromString(complexStr1);
ComplexNumber complex2 = ComplexNumber.fromString(complexStr2);
ComplexNumber expected = ComplexNumber.fromString(expectedStr);
ComplexNumber sum = complex1.divide(complex2);
Assertions.assertTrue(isSame(sum, expected));
}
public boolean isSame(ComplexNumber result, ComplexNumber expected){
return result.real() == expected.real() && result.imaginary() == expected.imaginary();
}
In the above implementation, we created a comprehensive test suite using @CsvSource to cover many complex number divisions. A custom utility method, isSame(), is implemented to compare the test results effectively. Similarly, we can implement the tests for other arithmetic operations with the same test parameters.
Additionally, we can also write an individual test to verify the divide-by-zero scenario:
@Test
public void givenAComplexNumberAsZero_handleDivideByZeroScenario() {
ComplexNumber complex1 = new ComplexNumber(1, 1);
ComplexNumber zero = new ComplexNumber(0, 0);
Exception exception = Assertions.assertThrows(ArithmeticException.class, () -> {
complex1.divide(zero);
});
Assertions.assertEquals(exception.getMessage(), "Division by 0 is not allowed!");
}
Here, we create a complex number where the real and imaginary parts are zero and then attempt to divide by it. Using assertThrows(), the test ensures an exception is thrown with the expected error message.
9. Conclusion
In this article, we implemented arithmetic operations on two complex numbers in Java. We explored addition, subtraction, multiplication, and division of complex numbers, implementing robust functionality through extensive test coverage. This includes utilizing parameterized tests to ensure the code functions correctly across various input values.
As always, the sample code used in this article is available over on GitHub.