```
/// <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;
}
```

**Are you able to help answer this sponsored question?**

Questions asked by members who have earned a lot of community kudos are featured in order to give back and encourage quality replies.

Recommended Topics