use of java.math.BigInteger in project guava by google.
the class LongMathTest method testCheckedAdd.
// slow
@AndroidIncompatible
// TODO
@GwtIncompatible
public void testCheckedAdd() {
for (long a : ALL_LONG_CANDIDATES) {
for (long b : ALL_LONG_CANDIDATES) {
BigInteger expectedResult = valueOf(a).add(valueOf(b));
boolean expectedSuccess = fitsInLong(expectedResult);
try {
assertEquals(a + b, LongMath.checkedAdd(a, b));
assertTrue(expectedSuccess);
} catch (ArithmeticException e) {
if (expectedSuccess) {
failFormat("expected checkedAdd(%s, %s) = %s; got ArithmeticException", a, b, expectedResult);
}
}
}
}
}
use of java.math.BigInteger in project guava by google.
the class LongMathTest method computeMeanSafely.
/**
* Computes the mean in a way that is obvious and resilient to
* overflow by using BigInteger arithmetic.
*/
private static long computeMeanSafely(long x, long y) {
BigInteger bigX = BigInteger.valueOf(x);
BigInteger bigY = BigInteger.valueOf(y);
BigDecimal bigMean = new BigDecimal(bigX.add(bigY)).divide(BigDecimal.valueOf(2), BigDecimal.ROUND_FLOOR);
// parseInt blows up on overflow as opposed to intValue() which does not.
return Long.parseLong(bigMean.toString());
}
use of java.math.BigInteger in project guava by google.
the class LongMathTest method testCheckedPow.
// TODO
@GwtIncompatible
public void testCheckedPow() {
for (long b : ALL_LONG_CANDIDATES) {
for (int exp : EXPONENTS) {
BigInteger expectedResult = valueOf(b).pow(exp);
boolean expectedSuccess = fitsInLong(expectedResult);
try {
assertEquals(expectedResult.longValue(), LongMath.checkedPow(b, exp));
assertTrue(expectedSuccess);
} catch (ArithmeticException e) {
if (expectedSuccess) {
failFormat("expected checkedPow(%s, %s) = %s; got ArithmeticException", b, exp, expectedResult);
}
}
}
}
}
use of java.math.BigInteger in project guava by google.
the class LongMathTest method testBinomial.
// Depends on the correctness of BigIntegerMath.binomial.
public void testBinomial() {
for (int n = 0; n <= 70; n++) {
for (int k = 0; k <= n; k++) {
BigInteger expectedBig = BigIntegerMath.binomial(n, k);
long expectedLong = fitsInLong(expectedBig) ? expectedBig.longValue() : Long.MAX_VALUE;
assertEquals(expectedLong, LongMath.binomial(n, k));
}
}
}
use of java.math.BigInteger in project guava by google.
the class IntMathTest method testFactorial.
// Depends on the correctness of BigIntegerMath.factorial.
public void testFactorial() {
for (int n = 0; n <= 50; n++) {
BigInteger expectedBig = BigIntegerMath.factorial(n);
int expectedInt = fitsInInt(expectedBig) ? expectedBig.intValue() : Integer.MAX_VALUE;
assertEquals(expectedInt, IntMath.factorial(n));
}
}
Aggregations