功能说明
最小二乘拟合用于趋势分析和简单预测。该函数接收 x/y 点数组,计算均值、协方差与方差,返回斜率、截距、R² 以及 predict 方法。x 值全部相同时无法定义唯一斜率,会抛错。返回值可以直接用于绘制趋势线或估算下一个数据点。
关键代码
一次循环累加 dx、dy、dx 乘 dy、dx 平方和 dy 平方。斜率等于分子除以分母,截距由均值推出。R² 用相关平方计算;当 y 全部相同且拟合完美时返回 1。predict 闭包使用斜率和截距,不修改原始点数组。
const slope = numerator / denominator;
const intercept = meanY - slope * meanX;
const rSquared = total === 0 ? 1 : (numerator * numerator) / (denominator * total);
return { slope, intercept, rSquared, predict: (x) => intercept + slope * x };
使用注意
该实现只做一元线性回归,不检测异常值或非线性关系。点数少于 2 或 x 全相同会抛错。R² 可能因浮点误差略超出 0 到 1。预测超出样本范围属于外推,需谨慎解释。坐标必须是有限数字,缺失值应先清洗。
验证方式
断言对 [(1, 2), (2, 4), (3, 6)] 拟合得到 slope 2、intercept 0、rSquared 1,predict(4) 为 8。x 全相同抛 RangeError,点数不足抛 RangeError。非有限坐标抛 TypeError。对负斜率数据应返回负 slope 且 R² 接近 1。