C# function to calculate polynomial coefficients from roots

949 Views Asked by At

I am looking for a simple method/function to calculate polynomial coefficients given the polynomial roots in C#. For example, given the roots: roots = [-3+j, -3-j, -5, -1] calculate a polynomial in the form x^4 + ax^3 + bx^2 + cx + d = 0, with the result being given as coefficients = [a, b, c, d]. In Python, numpy.poly(roots) can simply be used for this. I've looked for an equivalent C# function, but haven't found anything. Does anyone know of something like this?

1

There are 1 best solutions below

1
Ruslan Gilmutdinov On BEST ANSWER

The following method extracts coefficients of a polynomial that has the specified roots:

// vieta's formulas to calculate polynomial coefficients from roots
public static Complex[] FromRoots(Complex[] roots)
{
    int n = roots.Length;
    Complex[] coeffs = new Complex[n + 1];
    coeffs[n] = 1.0;

    for (int i = 0; i < n; i++)
    {
        for (int j = n - i - 1; j < n; j++)
        {
            coeffs[j] = coeffs[j] - roots[i] * coeffs[j + 1];
        }
    }

    Array.Reverse(coeffs);
    return coeffs;
}

You can use it in the following way:

Complex[] roots =
{
    new Complex(-3, 1),
    new Complex(-3, -1),
    -5,
    -1
};

Complex[] poly = FromRoots(roots);

// code below prints: (1, 0) (12, 0) (51, 0) (90, 0) (50, 0)
foreach (Complex p in poly)
{
    Console.Write(p + " ");
}