/**
 * Combination calculation with straightforward way using BigDecimal. "n" choose "k".
 * @param n
 * @param k
 * @return
 */
public static double mathCombination(int n, int k) {
	java.math.BigDecimal f_n_k = new java.math.BigDecimal(Ts.mathFactorial(n - k));
	java.math.BigDecimal f_k = new java.math.BigDecimal(Ts.mathFactorial(k));
	java.math.BigDecimal denominator = f_n_k.multiply(f_k);
	return Ts.mathFactorial(n) / denominator.doubleValue();
}
 
/**
 * Factorial calculation with straightforward way.
 * @param num
 * @return
 */
public static double mathFactorial(int num) {
	//----- to prevent abnormal result
	Ts.assertTrue(num >= 0 && num <= 143, "factorial: the range is from 0 to 143");
	double result = 1;
	for (int i = 1; i <= num; i++) {
		result *= i;
	}
	return result;
}
 
public static void assertTrue(boolean isTrue, String message) {
	if (!isTrue) {
		System.out.println("---> Assert fail : " + message);
		new Exception().printStackTrace();
		System.exit(-1);
	}
}


Back to JavaHowTo

Alumni Liaison

BSEE 2004, current Ph.D. student researching signal and image processing.

Landis Huffman