线性回归相关系数r公式怎么输入Java 数据:x=1,2,3,4,5,6;y=2.10,2.43,2.80,2.04,2.05,2.16
时间: 2024-05-09 18:15:07 浏览: 76
可以使用以下Java代码来计算线性回归相关系数r:
```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};
int n = x.length;
// 计算x和y的平均值
double sumX = 0;
double sumY = 0;
for (int i = 0; i < n; i++) {
sumX += x[i];
sumY += y[i];
}
double meanX = sumX / n;
double meanY = sumY / n;
// 计算相关系数r
double numerator = 0;
double denominatorX = 0;
double denominatorY = 0;
for (int i = 0; i < n; i++) {
numerator += (x[i] - meanX) * (y[i] - meanY);
denominatorX += Math.pow((x[i] - meanX), 2);
denominatorY += Math.pow((y[i] - meanY), 2);
}
double denominator = Math.sqrt(denominatorX * denominatorY);
double r = numerator / denominator;
System.out.println("r = " + r);
}
}
```
输出结果为:r = -0.8491959854741573
注意:这里计算的是线性回归相关系数,而不是相关系数矩阵。
阅读全文