如何在JavaScript中计算多项式展开系数 [英] How to calculate coefficients of polynomial expansion in javascript

查看:103
本文介绍了如何在JavaScript中计算多项式展开系数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下因素:

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

展开为多项式,它看起来像:

Expanded to a polynomial, it looks like:

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

该多项式的系数为

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];

我想做的是找到一种方法,可以快速地从因子转换为系数数组.关于如何在javascript中快速处理此问题的任何建议?为了清楚起见,我试图找出如何针对任意n个因素(不仅限于此特定情况)进行此操作.

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.

推荐答案

您可以将因子用作向量,并对结果使用叉积.

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

这篇关于如何在JavaScript中计算多项式展开系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆