JS 计算两组数据的斜率、截距和R^2

 let r=XGX.pearson([0.3,50.2,99.5,199.3,299,398],[0.1,50,99.9,200,300,400]);
          let slope=XGX.slope([0.3,50.9,100.8,200,300,400],[0.2,50,100.2,200,300,400]);
          let intercept=XGX.intercept([0.3,50.2,99.5,199.3,299,398],[0.1,50,99.9,200,300,400]);

let XGX= {
    /**
     * 计算皮尔逊相关系数
     * @list1:数字列表1
     * @list2:数字列表2
     * @return number
    * */
    pearson(list1,list2){
        let newList = [];
        let len = list1.length;
        for(let i=0;i{sum+=item})
        return sum/list.length;
    },
    /**
     * 计算标准差
     * @list:数字列表
     * @mean:列表list的平均值
     * @return number
     * */
    std(list,mean){
        let sum =0;
        list.forEach((item)=>{sum+=Math.pow(item-mean,2)})
        return Math.sqrt(sum/list.length)
    },
    slope(x,y){
        let sum_x = 0, sum_y = 0, sum_xy = 0, sum_xx = 0;       
        for (let i = 0; i < x.length; i++)
        {
            sum_x += x[i];
            sum_y += y[i];
            sum_xy += x[i] * y[i];
            sum_xx += x[i] * x[i];
        }      
        let slope = (x.length * sum_xy - sum_x * sum_y) / (x.length * sum_xx - sum_x * sum_x);
        return slope;
    },
    intercept(x,y){
        let sum_x = 0, sum_y = 0, sum_xy = 0, sum_xx = 0;       
        for (let i = 0; i < x.length; i++)
        {
            sum_x += x[i];
            sum_y += y[i];
            sum_xy += x[i] * y[i];
            sum_xx += x[i] * x[i];
        }      
        let slope = (x.length * sum_xy - sum_x * sum_y) / (x.length * sum_xx - sum_x * sum_x);
        let intercept = (sum_y - slope * sum_x) / x.length;
        return intercept;
    },
    r_squared(){
        let sum_x = 0, sum_y = 0, sum_xy = 0, sum_xx = 0;       
        for (let i = 0; i < x.length; i++)
        {
            sum_x += x[i];
            sum_y += y[i];
            sum_xy += x[i] * y[i];
            sum_xx += x[i] * x[i];
        }      
        let slope = (x.length * sum_xy - sum_x * sum_y) / (x.length * sum_xx - sum_x * sum_x);
        let intercept = (sum_y - slope * sum_x) / x.length;
        let y_mean = sum_y / y.length;
        let ss_tot = 0, ss_res = 0;
        for (let i = 0; i < x.length; i++)
        {
            let y_pred = slope * x[i] + intercept;
            ss_tot += (y[i] - y_mean) * (y[i] - y_mean);
            ss_res += (y[i] - y_pred) * (y[i] - y_pred);
        }
        let r_squared = 1 - ss_res / ss_tot;
        return r_squared;
    },
};
export default XGX

你可能感兴趣的:(前端,javascript,r语言,c#)