MATH-894
Introducing new interface for operating on a "double[]" (added in the "MathArrays" class). Using this interface, operations can be performed on the internal array of a "ResizeableDoubleArray" through a new "compute" method. Thanks to Phil Steitz. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/math/trunk@1410121 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
parent
4870a5d99d
commit
b7555df622
|
@ -47,6 +47,28 @@ public class MathArrays {
|
|||
*/
|
||||
private MathArrays() {}
|
||||
|
||||
/**
|
||||
* Real-valued function that operate on an array or a part of it.
|
||||
*/
|
||||
public interface Function {
|
||||
/**
|
||||
* Operates on an entire array.
|
||||
*
|
||||
* @param array Array to operate on.
|
||||
* @return the result of the operation.
|
||||
*/
|
||||
double evaluate(double[] array);
|
||||
/**
|
||||
* @param array Array to operate on.
|
||||
* @param startIndex Index of the first element to take into account.
|
||||
* @param numElements Number of elements to take into account.
|
||||
* @return the result of the operation.
|
||||
*/
|
||||
double evaluate(double[] array,
|
||||
int startIndex,
|
||||
int numElements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the L<sub>1</sub> (sum of abs) distance between two points.
|
||||
*
|
||||
|
|
|
@ -805,6 +805,15 @@ public class ResizableDoubleArray implements DoubleArray, Serializable {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs an operation on the addressable elements of the array.
|
||||
*
|
||||
* @param f Function to be applied on this array.
|
||||
* @return the result.
|
||||
*/
|
||||
public double compute(MathArrays.Function f) {
|
||||
return f.evaluate(internalArray, startIndex, numElements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the element at the specified index. If the specified index is greater than
|
||||
|
|
|
@ -558,6 +558,32 @@ public class ResizableDoubleArrayTest extends DoubleArrayAbstractTest {
|
|||
Assert.assertEquals(v2, a.getElement(index), 0d);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCompute() {
|
||||
final ResizableDoubleArray a = new ResizableDoubleArray();
|
||||
final int max = 20;
|
||||
for (int i = 1; i <= max; i++) {
|
||||
a.setElement(i, i);
|
||||
}
|
||||
|
||||
final MathArrays.Function add = new MathArrays.Function() {
|
||||
public double evaluate(double[] a, int index, int num) {
|
||||
double sum = 0;
|
||||
final int max = index + num;
|
||||
for (int i = index; i < max; i++) {
|
||||
sum += a[i];
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
public double evaluate(double[] a) {
|
||||
return evaluate(a, 0, a.length);
|
||||
}
|
||||
};
|
||||
|
||||
final double sum = a.compute(add);
|
||||
Assert.assertEquals(0.5 * max * (max + 1), sum, 0);
|
||||
}
|
||||
|
||||
private void verifyEquality(ResizableDoubleArray a, ResizableDoubleArray b) {
|
||||
Assert.assertTrue(b.equals(a));
|
||||
Assert.assertTrue(a.equals(b));
|
||||
|
|
Loading…
Reference in New Issue