Repository navigation
Arithmetic Operations
This library comes with a variety of arithmetic operations.
If the operation ends in "eq", that means it applies the operation to whichever Complex number this was applied on. For instance, the statement:
A.addeq(new Complex(1,1))
is equivalent to:
A += 1+i
On the other hand, if the operation doesn't end in "eq", then the inputs are completely unaffected by the operation and the result is recorded on a new instance of the Complex class.
add - returns the sum of two Complexes or of one Complex and one double
sub - returns the difference between two Complexes or between one Complex and one double
mul - returns the product between two Complexes, or between one Complex and one double
div - returns the quotient between two Complexes, or between one Complex and one double
addeq - adds the second number to the first number and returns the sum
subeq - subtracts the second number from the first and returns the result
muleq - multiplies the first number by the second and returns the result
diveq - divides the first number by the second and returns the result
All of these operations, except div and diveq, use very primitive implementations. add, sub, addeq, and subeq all simply add/subtract the real and imaginary components. mul and muleq utilize the distributive property when operating on two complexes, and may be subject to unavoidable roundoff in some cases. When operating on one double and one complex, however, mul and muleq simply multiply each component by that double.
div and diveq are a bit different, however. When performing on a Complex and double, the computer must first check if the double is a denormal. If not, we simply calculate the reciprocal of the double and multiply each component by that reciprocal. If it is a denormal, however, the reciprocal is an overflow, and we instead have to divide each component by that double.
When performing on two complexes, the divide operations become even more complicated. We first have to compute the inverse of the divisor, then multiply that by the dividend. Computing the reciprocal of the divisor requires utilizing the inv function.
The add, sub, mul, and div functions are also defined within the Cpx class. This external implementation is helpful so that we can subtract a complex from a double, or so that we can take a double divided by a complex. It's also helpful as it allows us to define add and mul functions with unlimited inputs. Since addition and multiplication are commutative and associative, the library makes use of varargs to allow for an unlimited input add and mul function, so the user doesn't have to chain together a long series of adds and muls.