Centroid { static double[] getCentroid(final double[][] points) { if (Arrays.stream(points).mapToInt(p -> p.length).distinct().count() != 1) { throw new IllegalArgumentException( "Points must have the same dimensionality"); } final int nDimensions = points[0].length; final double[] centroid = new double[nDimensions]; for (final double[] point : points) { for (int d = 0; d < nDimensions; d++) { centroid[d] += point[d]; } } for (int i = 0; i < centroid.length; i++) { centroid[i] /= points.length; } return centroid; } private  Centroid();   }
@Test public void testGetCentroidDoubleArrayArray() { try { Centroid.getCentroid(badNd); fail("Should throw IllegalArgumentException"); } catch (final IllegalArgumentException e) { } final double[] centroid = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; assertArrayEquals(centroid, Centroid.getCentroid(goodNd), 1E-9); final double[][] threeD = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 }, { 13, 14, 15 }, { 16, 17, 18 } }; final double[] centroid3d = { 8.5, 9.5, 10.5 }; assertArrayEquals(centroid3d, Centroid.getCentroid(threeD), 1E-9); final double[][] twoD = { { 1, 2 }, { 4, 5 }, { 7, 8 }, { 10, 11 }, { 13, 14 }, { 16, 17 } }; final double[] centroid2d = { 8.5, 9.5 }; assertArrayEquals(centroid2d, Centroid.getCentroid(twoD), 1E-9); final double[][] oneD = { { 1 }, { 4 }, { 7 }, { 10 }, { 13 }, { 16 } }; final double[] centroid1d = { 8.5 }; assertArrayEquals(centroid1d, Centroid.getCentroid(oneD), 1E-9); }