Added MathUtil.floorDiv, and tests.
This commit is contained in:
@@ -17,4 +17,20 @@ public class MathUtil
|
||||
if (value > high) return high;
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the floored division {@code dividend/divisor} which is useful when dividing
|
||||
* potentially negative numbers into bins.
|
||||
*
|
||||
* <p> For example, the following numbers {@code floorDiv} 10 are:
|
||||
* <pre>
|
||||
* -15 -10 -8 -2 0 2 8 10 15
|
||||
* -2 -1 -1 -1 0 0 0 1 1
|
||||
* </pre>
|
||||
*/
|
||||
public static int floorDiv (int dividend, int divisor) {
|
||||
boolean numpos = dividend >= 0, denpos = divisor >= 0;
|
||||
if (numpos == denpos) return dividend / divisor;
|
||||
return denpos ? (dividend - divisor + 1) / divisor : (dividend - divisor - 1) / divisor;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
//
|
||||
// Pythagoras - a collection of geometry classes
|
||||
// http://github.com/samskivert/pythagoras
|
||||
|
||||
package pythagoras.i;
|
||||
|
||||
import org.junit.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* Tests parts of the {@link MathUtil} class.
|
||||
*/
|
||||
public class MathUtilTest
|
||||
{
|
||||
@Test public void testFloorDiv () {
|
||||
int[] nums = { -15, -10, -8, -2, 0, 2, 8, 10, 15 };
|
||||
int[] vals = { -2, -1, -1, -1, 0, 0, 0, 1, 1 };
|
||||
for (int ii = 0; ii < nums.length; ii++) {
|
||||
assertEquals(vals[ii], MathUtil.floorDiv(nums[ii], 10));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user