Search code examples
c#polynomialsmath.netcubic

find roots of cubic polynomial


I'm trying to find the roots of a cubic polynomial ax^3+bx^2+cx+d=0 using math.numerics. The package is great, but I'm struggling to get started with it. Please can someone explain how to find the roots, and a simple explanation on how to run the sample package from Github?

I've added a reference to the package

using MathNet.Numerics;

and this is what I've tried:

var roots = FindRoots.Cubic(d, c, b, a);
double root1=roots.item1;
double root2=roots.item2;
double root3=roots.item3;

but I get an error "The type 'Complex' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Numerics'". Adding using System.Numerics gives an error and doesn't solve the problem.

Any suggestions please?


Solution

  • If you're using Visual Studio, you need to right-click the References folder for your project in Solution Explorer, click Add Reference, and then select System.Numerics from the Assemblies > Framework list:

    Screenshot of Reference Manager dialog box

    Because MathNet.Numerics.FindRoots.Cubic returns roots as complex numbers, you must use the System.Numerics.Complex type instead of double to store your roots:

    using System.Numerics;
    using MathNet.Numerics;
    
    class Program
    {
        static void Main()
        {
            double d = 0, c = -1, b = 0, a = 1; // x^3 - x
            var roots = FindRoots.Cubic(d, c, b, a);
            Complex root1 = roots.Item1;
            Complex root2 = roots.Item2;
            Complex root3 = roots.Item3;
        }
    }
    

    If you only want to deal with real numbers, call MathNet.Numerics.RootFinding.Cubic.RealRoots instead (which will return any complex-valued roots as Double.NaN):

    using MathNet.Numerics.RootFinding;
    ...
    var roots = Cubic.RealRoots(d, c, b); // "a" is assumed to be 1
    double root1 = roots.Item1;
    double root2 = roots.Item2;
    double roo13 = roots.Item3;