常用统计算法JAVA实现 - 相关系数(08)

/**
	 * 
	 *@描述: 相关系数 
*@方法名: correlation
*@param x
*@param y
*@return  * @返回类型 double 返回值[-1,1]{[-1,0]负相关;[0,1]正相关}, 取绝对值,越大表示相关性越强, * .8~1: 非常强 ,.6~.8: 强相关 ,.4~.6: 中度相关,.2~.4: 弱相关,.0~.: 弱相关或者无关
* @创建人 micheal
*@创建时间 2019年1月3日下午8:51:27
*@修改人 micheal
*@修改时间 2019年1月3日下午8:51:27
*@修改备注
*@since
*@throws
*   */ public static double correlation(double[] x, double[] y) { if (x.length != y.length) { throw new java.lang.NumberFormatException(); } double xSum = 0; double ySum = 0; double xP2Sum = 0; double yP2Sum = 0; double xySum = 0; int len = x.length; for (int i = 0; i < y.length; i++) { xSum = Mutil.add(xSum, x[i]); ySum = Mutil.add(ySum, y[i]); xP2Sum = Mutil.add(xP2Sum, Math.pow(x[i], 2)); yP2Sum = Mutil.add(yP2Sum, Math.pow(y[i], 2)); xySum = Mutil.add(xySum, Mutil.multiply(x[i], y[i])); } double Rxy = Mutil.subtract(Mutil.multiply(len, xySum), Mutil.multiply(xSum, ySum)) / (Math.sqrt((Mutil.multiply(len, xP2Sum) - Math.pow(xSum, 2)) * (Mutil.multiply(len, yP2Sum) - Math.pow(ySum, 2)))); return Mutil.round(Rxy, 2); }

测试代码,打印结果,相关性:0.69

double[] x = { 2, 4, 5, 6, 4, 7, 8, 5, 6, 7 };
double[] y = { 3, 2, 6, 5, 3, 6, 5, 4, 4, 5 };
log.info("计算[相关性]:" + correlation(x, y));

 

你可能感兴趣的:(相关系数)