java实现最小二乘法(附完整源码)
时间: 2023-11-11 08:03:24 浏览: 166
以下是Java实现最小二乘法的完整源码,供参考:
```
public class LeastSquares {
public static void main(String[] args) {
double[] x = {1, 2, 3, 4, 5};
double[] y = {1, 3, 5, 7, 9};
double[] result = leastSquares(x, y);
System.out.println("y = " + result[0] + "x + " + result[1]);
}
public static double[] leastSquares(double[] x, double[] y) {
int n = x.length; // 样本数
double sumX = 0.0; // x的和
double sumY = 0.0; // y的和
double sumXY = 0.0; // x*y的和
double sumXX = 0.0; // x^2的和
// 计算x、y、xy、xx的和
for (int i = 0; i < n; i++) {
sumX += x[i];
sumY += y[i];
sumXY += x[i] * y[i];
sumXX += x[i] * x[i];
}
// 计算斜率k和截距b
double k = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);
double b = (sumY - k * sumX) / n;
double[] result = {k, b};
return result;
}
}
```
该代码实现了最小二乘法的算法,接收两个数组x和y作为输入,计算线性回归方程的斜率k和截距b,最后输出结果。
阅读全文