コイン投げ #8

現在二種類のアイテムそれぞれの獲得数は18個*1と27個である。
獲得確率が等しいとすれば、獲得数差が7個以内となるような確率は、
\sum_{m=18+1}^{27-1}{18+27 \choose m} \times 2^{-(18+27)} \approx 0.767307
であり、これの余事象が起こることが稀であるというほどではまだない。

この値を非効率的に求めるにはJavaなら次のようなコードでいい。

import java.math.BigDecimal;
import java.math.BigInteger;

public class Foo {
    public static void main(String[] args) {
        System.out.println(prob(18, 27, 6));
    }

    private static BigDecimal prob(int a, int b, int scale) {
        if (a < 0 || b < 0) throw new IllegalArgumentException("negative argguments");
        if (a > b) throw new IllegalArgumentException("reverse ordered arguments");
        BigInteger x = BigInteger.ZERO;
        for (int m = a + 1; m < b; m++) {
            x = x.add(comb(a + b, m));
        }
        BigInteger y = BigInteger.valueOf(2).pow(a + b);
        return new BigDecimal(x).divide(new BigDecimal(y), scale, BigDecimal.ROUND_HALF_UP);
    }

    private static BigInteger fact(int n) {
        if (n < 0) throw new IllegalArgumentException("negative factorial");
        BigInteger x = BigInteger.ONE;
        for (int i = 2; i <= n; i++) x = x.multiply(BigInteger.valueOf(i));
        return x;
    }

    private static BigInteger comb(int n, int m) {
        if (n < 0 || m < 0) throw new IllegalArgumentException("negative combination");
        return fact(n).divide(fact(m)).divide(fact(n - m));
    }
}

*1:まだ20個にすら達していない!