Skip to content
Advertisement

How to calculate coefficients of polynomial expansion in javascript

Suppose I have the following factors:

(1+3x)(1+x)(1+2x)

Expanded to a polynomial, it looks like:

1 + 6x + 11x^2 + 6x^3

The coefficients of this polynomial would be

c0 = 1
c1 = 6
c2 = 11
c3 = 6

I’m trying to figure out how to calculate these rapidly (for any set of factors). The ideal output would be an array of the coefficients, like

var coeff = [c0,c1,c2,c3];

What I’m trying to do is find a way to quickly go from the factors to the array of coefficients. Any suggestions on how to rapidly handle this in javascript? And for the sake of clarity, I’m trying to figure out how to do this for any set of n factors, not just this particular scenario.

Advertisement

Answer

You could use the factors as vector and use a cross product for the result.

function multiply(a1, a2) {
    var result = [];
    a1.forEach(function (a, i) {
        a2.forEach(function (b, j) {
            result[i + j] = (result[i + j] || 0) + a * b;
        });
    });
    return result;
}

var data = [[1, 3], [1, 1], [1, 2]], // (1+3x)(1+x)(1+2x)
    result = data.reduce(multiply);
    
console.log(result);                 // [1, 6, 11, 6] = 1x^0 + 6x^1 + 11x^2 + 6x^3
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement