Reputation: 699
I have a question. I wrote the operator in C++, which divides complex numbers.
friend const Comp operator/(const Comp& x, const Comp& y)
{
Comp temp;
temp.real = ((x.real * y.real) + (x.imag * y.imag))/(y.real*y.real + y.imag*y.imag);
temp.imag = ((x.imag * y.real) - (x.real * y.imag))/(y.real*y.real + y.imag*y.imag);
return temp;
}
And I think about one thing. Is there any situation that we can't divide complex numbers? If yes, I will probably use std:cerr, because in normal division divider must be != 0, so here this part must be != 0 (y.realy.real + y.imagy.imag)???
Upvotes: 0
Views: 3331
Reputation: 4431
Mathematically speaking, you can always divide by any complex number other than 0.
However naively implementing the mathematical formula leads to code that will not perform as well as it might.
In your implementation for example the computation of the denominator could overflow to infinity or underflow to 0, even though both the real and imaginary parts of y are non zero and finite.
If your aim is to produce 'production quality' code, you might want to search the web for 'complex division algorithm' or the like, or take a look at the glibc sources.
Upvotes: 2
Reputation: 118017
Is there any situation that we can't divide complex numbers?
If you go for creating your own class for dealing with complex numbers instead of using std::complex
, try to make it behave like a user would expect. That is:
n/d
when n != 0
and d == 0
gives inf, inf
(or possibly -inf, -inf
).n/d
when both are 0 gives nan, nan
(or possibly -nan, -nan
).This is unrelated to the question but nevertheless related to the usability and maintainability of your class:
The signature:
friend const Comp operator/(const Comp& x, const Comp& y)
The Comp
returned by value from this function should not be const
. Making it const
will force an expression like:
Comp result = complex1 / complex2;
to copy the result returned by the function. Leave the const
out and copy elision (or NRVO - Named Return Value Optimization) is kicking in.
The implementation:
You should typically start by implementing the member function
Comp& operator/=(const Comp& rhs);
that divides *this
with rhs
(and returns *this
). The free friend
function could then be implemented like this:
friend Comp operator/(const Comp& x, const Comp& y) {
Comp temp(x); // copy construction
temp /= y; // operator/=
return temp; // NRVO
}
Upvotes: 3