Skip to content

Commit 832ae49

Browse files
authored
Enhance comments in correlation function
Added detailed comments to the correlation function for better understanding.
1 parent e037c7b commit 832ae49

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

src/main/java/com/thealgorithms/maths/Correlation.java

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ private Correlation() {
1212

1313
/**
1414
* Discrete correlation function.
15-
* Correlation between two discrete variables is calculated.
15+
* Correlation between two discrete variables is calculated
16+
* according to the formula: Cor(x, y)=Cov(x, y)/sqrt(Var(x)*Var(y)).
1617
* Correlation with a constant variable is taken to be zero.
1718
*
1819
* @param x The first discrete variable
@@ -21,11 +22,11 @@ private Correlation() {
2122
* @return The result of the correlation of variables x,y.
2223
*/
2324
public static double correlation(double[] x, double[] y, int n) {
24-
double exy = 0;
25-
double ex = 0;
26-
double exx = 0;
27-
double ey = 0;
28-
double eyy = 0;
25+
double exy = 0; //E(XY)
26+
double ex = 0; //E(X)
27+
double exx = 0; //E(X^2)
28+
double ey = 0; //E(Y)
29+
double eyy = 0; //E(Y^2)
2930
for (int i = 0; i < n; i++) {
3031
exy += x[i] * y[i];
3132
ex += x[i];
@@ -38,10 +39,10 @@ public static double correlation(double[] x, double[] y, int n) {
3839
exx /= n;
3940
ey /= n;
4041
eyy /= n;
41-
double cov = exy - ex * ey;
42-
double varx = Math.sqrt(exx - ex * ex);
43-
double vary = Math.sqrt(eyy - ey * ey);
44-
if (varx * vary < DELTA) {
42+
double cov = exy - ex * ey; //Cov(X, Y) = E(XY)-E(X)E(Y)
43+
double varx = Math.sqrt(exx - ex * ex); //Var(X) = sqrt(E(X^2)-E(X)^2)
44+
double vary = Math.sqrt(eyy - ey * ey); //Var(Y) = sqrt(E(Y^2)-E(Y)^2)
45+
if (varx * vary < DELTA) { //Var(X) = 0 means X = const, the same about Y
4546
return 0;
4647
} else {
4748
return cov / Math.sqrt(varx * vary);

0 commit comments

Comments
 (0)