MATH-1130

Method "copyOfRange" (available as of Java 6 in "java.util.Arrays").


git-svn-id: https://svn.apache.org/repos/asf/commons/proper/math/trunk@1604172 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Gilles Sadowski 2014-06-20 13:37:42 +00:00
parent 0714c7cbe6
commit 44b5c55e07
2 changed files with 38 additions and 0 deletions

View File

@ -798,6 +798,21 @@ public class MathArrays {
return output;
}
/**
* Creates a copy of the {@code source} array.
*
* @param source Array to be copied.
* @param from Initial index of the range to be copied, inclusive.
* @param to Final index of the range to be copied, exclusive. (This index may lie outside the array.)
* @return the copied array.
*/
public static double[] copyOfRange(double[] source, int from, int to) {
final int len = to - from;
final double[] output = new double[len];
System.arraycopy(source, from, output, 0, FastMath.min(len, source.length - from));
return output;
}
/**
* Compute a linear combination accurately.
* This method computes the sum of the products

View File

@ -588,6 +588,29 @@ public class MathArraysTest {
}
}
@Test
public void testCopyOfRange() {
final double[] source = { Double.NEGATIVE_INFINITY,
-Double.MAX_VALUE,
-1, 0,
Double.MIN_VALUE,
FastMath.ulp(1d),
1, 3, 113, 4769,
Double.MAX_VALUE,
Double.POSITIVE_INFINITY };
final int from = 3;
final int to = source.length + 14;
final double[] dest = MathArrays.copyOfRange(source, from, to);
Assert.assertEquals(dest.length, to - from);
for (int i = from; i < source.length; i++) {
Assert.assertEquals(source[i], dest[i - from], 0);
}
for (int i = source.length; i < dest.length; i++) {
Assert.assertEquals(0, dest[i - from], 0);
}
}
// MATH-1005
@Test
public void testLinearCombinationWithSingleElementArray() {