From 40e039428dce7c4d4ffe197e12df6aaf3eda9492 Mon Sep 17 00:00:00 2001 From: Mahammad Insaf Date: Tue, 17 Nov 2026 18:47:45 +0530 Subject: [PATCH] count signed zeros as ties in KendallsCorrelation correlation boxes the values into Pair and detects ties with Double.equals and orders them with Double.compareTo, which both treat -0.0 and 0.0 as different values. A pair whose x or y values are 0.0 and -0.0 was counted as concordant or discordant instead of tied, so correlation({0.0, -0.0, 1.0}, {1, 2, 3}) returned 1/3 instead of 2/sqrt(6). Map -0.0 to 0.0 when the pairs are built. --- .../legacy/stat/correlation/KendallsCorrelation.java | 3 ++- .../stat/correlation/KendallsCorrelationTest.java | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/stat/correlation/KendallsCorrelation.java b/commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/stat/correlation/KendallsCorrelation.java index 862949336e..7b2b16be94 100644 --- a/commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/stat/correlation/KendallsCorrelation.java +++ b/commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/stat/correlation/KendallsCorrelation.java @@ -164,7 +164,8 @@ public double correlation(final double[] xArray, final double[] yArray) @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { - pairs[i] = new Pair<>(xArray[i], yArray[i]); + // Adding 0.0 maps -0.0 to 0.0 so that signed zeros are counted as ties + pairs[i] = new Pair<>(xArray[i] + 0.0, yArray[i] + 0.0); } Arrays.sort(pairs, new Comparator>() { diff --git a/commons-math-legacy/src/test/java/org/apache/commons/math4/legacy/stat/correlation/KendallsCorrelationTest.java b/commons-math-legacy/src/test/java/org/apache/commons/math4/legacy/stat/correlation/KendallsCorrelationTest.java index 722ffdc458..1ae5bc36e1 100644 --- a/commons-math-legacy/src/test/java/org/apache/commons/math4/legacy/stat/correlation/KendallsCorrelationTest.java +++ b/commons-math-legacy/src/test/java/org/apache/commons/math4/legacy/stat/correlation/KendallsCorrelationTest.java @@ -216,6 +216,16 @@ public void testTwoElements() { Assert.assertEquals(-1.0, correlation.correlation(xArray, yArray), Double.MIN_VALUE); } + @Test + public void testSignedZeroTies() { + // -0.0 and 0.0 are the same value and must be counted as a tie + final double[] xArray = new double[] {0.0, -0.0, 1.0}; + final double[] yArray = new double[] {1.0, 2.0, 3.0}; + Assert.assertEquals(2 / Math.sqrt(6), correlation.correlation(xArray, yArray), 1e-15); + Assert.assertEquals(2 / Math.sqrt(6), correlation.correlation(yArray, xArray), 1e-15); + Assert.assertEquals(Double.NaN, correlation.correlation(new double[] {0.0, -0.0}, new double[] {1.0, 2.0}), 0); + } + @Test public void test2dDoubleArray() { final double[][] input = new double[][] {