How do I create a best-fit polynomial curve in Javascript?

前端 未结 1 1412
不知归路
不知归路 2021-02-06 10:24

I\'m trying to calculate a best-fit curve for data using a 3-6 order polynomial. I found this tutorial: Cubic Regression (best fit line) in JavaScript

First, I can\'t

相关标签:
1条回答
  • 2021-02-06 10:56

    Figured it out using Matrix Algebra:

    var x = [500,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500,6000,6500,7000];
    var y = [50,80,100,160,210,265,340,390,440,470,500,500,495,460];
    
    order = 3;
    
    var xMatrix = [];
    var xTemp = [];
    var yMatrix = numeric.transpose([y]);
    
    for (j=0;j<x.length;j++)
    {
        xTemp = [];
        for(i=0;i<=order;i++)
        {
            xTemp.push(1*Math.pow(x[j],i));
        }
        xMatrix.push(xTemp);
    }
    
    var xMatrixT = numeric.transpose(xMatrix);
    var dot1 = numeric.dot(xMatrixT,xMatrix);
    var dotInv = numeric.inv(dot1);
    var dot2 = numeric.dot(xMatrixT,yMatrix);
    var solution = numeric.dot(dotInv,dot2);
    console.log("Coefficients a + bx^1 + cx^2...")
    console.log(solution);
    

    jsbin: http://jsbin.com/yoqiqanofo/1/

    0 讨论(0)
提交回复
热议问题