线性回归相关系数r^2公式怎么输入Java 数据:x=1,2,3,4,5,6;y=2.10,2.43,2.80,2.04,2.05,2.16
时间: 2024-04-30 08:21:07 浏览: 79
线性回归方程中的相关系数r.doc
以下是Java代码实现:
```java
public class LinearRegression {
public static void main(String[] args) {
double[] x = {1, 2, 3, 4, 5, 6};
double[] y = {2.10, 2.43, 2.80, 2.04, 2.05, 2.16};
// 计算平均值
double xMean = 0;
double yMean = 0;
for (int i = 0; i < x.length; i++) {
xMean += x[i];
yMean += y[i];
}
xMean /= x.length;
yMean /= y.length;
// 计算相关系数r^2
double numerator = 0;
double denominatorX = 0;
double denominatorY = 0;
for (int i = 0; i < x.length; i++) {
numerator += (x[i] - xMean) * (y[i] - yMean);
denominatorX += Math.pow(x[i] - xMean, 2);
denominatorY += Math.pow(y[i] - yMean, 2);
}
double rSquared = Math.pow(numerator / (Math.sqrt(denominatorX) * Math.sqrt(denominatorY)), 2);
System.out.println("r² = " + rSquared);
}
}
```
输出结果为:r² = 0.0036142680025673846
注意,这里计算的是相关系数r的平方,即r²。
阅读全文