I am trying to divide two complex numbers in C# but can't get it to work! I'm pretty sure it is my formula that is wrong, but I do not understand what the problem is with it.
I have tried to modify the formula a few times but with no success. This is because I have never studied Complex numbers (or any math similar to it) and am therefore pretty lost. I tried this formula: http://www.mesacc.edu/~scotz47781/mat120/notes/complex/dividing/dividing_complex.html but had trouble converting it into code.
I am grateful for any responses! Thank you
public Komplex div(Komplex a, Komplex b)
{
Komplex resDiv = new Komplex();
resDiv.re = a.re / b.re - a.im / a.im;
resDiv.im = a.re / b.im + a.im / b.re;
return resDiv;
}
EDIT: The program is supposed to take inputs like this (example): (3+2i) / (1-4i)
This is how .NET's Complex
class does it (adjusted for your variable and type names):
public static Komplex div(Komplex a, Komplex b)
{
// Division : Smith's formula.
double a = a.re;
double b = a.im;
double c = b.re;
double d = b.im;
Komplex resDiv = new Komplex();
// Computing c * c + d * d will overflow even in cases where the actual result of the division does not overflow.
if (Math.Abs(d) < Math.Abs(c))
{
double doc = d / c;
resDiv.re = (a + b * doc) / (c + d * doc);
resDiv.im = (b - a * doc) / (c + d * doc);
}
else
{
double cod = c / d;
resDiv.re = (b + a * cod) / (d + c * cod);
resDiv.im = (-a + b * cod) / (d + c * cod);
}
return resDiv;
}
Why aren't you using .NET's Complex
type though?
var a = new Complex(3, -1);
var b = new Complex(5, -3);
Console.WriteLine(a / b);