Complex numbers are seldom used in daily life, altough you could say that every real number is complex, but with the imaginary part equal to zero. And btw. "complex" is a bit of a misnomer, perhaps we should call them "easies", because often they make it easier to perform certain math tasks.
It all started in Italy, 13th century or so when mathematicians where trying to solve quadratic and cubic equations. Here is my solution in C# of the cubic. I used the rules found in wikipedia.
Included a zip file with a small formsapplication that exercises the method given here.
Solving the cubic equation using the Complex struct
/// <summary>
/// Solve ax^3+bx^2+cx+d=0 for x.
/// Calculation of the 3 roots of a cubic equation according to
/// http://en.wikipedia.org/wiki/Cubic_function#General_formula_for_roots
/// Using the complex struct from System.Numerics
/// Visual Studio 2010, .NET version 4.0
/// </summary>
/// <param name="a">real coefficient of x to the 3th power</param>
/// <param name="b">real coefficient of x to the 2nd power</param>
/// <param name="c">real coefficient of x to the 1th power</param>
/// <param name="d">real coefficient of x to the zeroth power</param>
/// <returns>A list of 3 complex numbers</returns>
public List<Complex> SolveCubic(double a, double b, double c, double d)
{
const int NRoots = 3;
double SquareRootof3 = Math.Sqrt(3);
// the 3 cubic roots of 1
List<Complex> CubicUnity = new List<Complex>(NRoots)
{ new Complex(1, 0), new Complex(-0.5, -SquareRootof3 / 2.0), new Complex(-0.5, SquareRootof3 / 2.0) };
// intermediate calculations
double DELTA = 18 * a * b * c * d - 4 * b * b * b * d + b * b * c * c - 4 * a * c * c * c - 27 * a * a * d * d;
double DELTA0 = b * b - 3 * a * c;
double DELTA1 = 2 * b * b * b - 9 * a * b * c + 27 * a * a * d;
Complex DELTA2 = -27 * a * a * DELTA;
Complex C = Complex.Pow((DELTA1 + Complex.Pow(DELTA2, 0.5)) / 2, 1 / 3.0); //Phew...
List<Complex> R = new List<Complex>(NRoots);
for (int i = 0; i < NRoots; i++)
{
Complex M = CubicUnity[i] * C;
Complex Root = -1.0 / (3 * a) * (b + M + DELTA0 / M);
R.Add(Root);
}
return R;
}
Ketsuekiame 860 Master Poster Featured Poster
ddanbe 2,724 Professional Procrastinator Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.