Example #1
0
def test_binomial_symbolic():
    n = 2
    p = symbols('p', positive=True)
    X = Binomial('X', n, p)
    t = Symbol('t')

    assert simplify(E(X)) == n * p == simplify(moment(X, 1))
    assert simplify(variance(X)) == n * p * (1 - p) == simplify(cmoment(X, 2))
    assert cancel((skewness(X) - (1 - 2 * p) / sqrt(n * p * (1 - p)))) == 0
    assert cancel((kurtosis(X)) - (3 + (1 - 6 * p * (1 - p)) / (n * p *
                                                                (1 - p)))) == 0
    assert characteristic_function(X)(t) == p**2 * exp(
        2 * I * t) + 2 * p * (-p + 1) * exp(I * t) + (-p + 1)**2
    assert moment_generating_function(X)(
        t) == p**2 * exp(2 * t) + 2 * p * (-p + 1) * exp(t) + (-p + 1)**2

    # Test ability to change success/failure winnings
    H, T = symbols('H T')
    Y = Binomial('Y', n, p, succ=H, fail=T)
    assert simplify(E(Y) - (n * (H * p + T * (1 - p)))) == 0

    # test symbolic dimensions
    n = symbols('n')
    B = Binomial('B', n, p)
    raises(NotImplementedError, lambda: P(B > 2))
    assert density(B).dict == Density(BinomialDistribution(n, p, 1, 0))
    assert set(density(B).dict.subs(n, 4).doit().keys()) == \
    set([S(0), S(1), S(2), S(3), S(4)])
    assert set(density(B).dict.subs(n, 4).doit().values()) == \
    set([(1 - p)**4, 4*p*(1 - p)**3, 6*p**2*(1 - p)**2, 4*p**3*(1 - p), p**4])
    k = Dummy('k', integer=True)
    assert E(B > 2).dummy_eq(
        Sum(
            Piecewise((k * p**k * (1 - p)**(-k + n) * binomial(n, k), (k >= 0)
                       & (k <= n) & (k > 2)), (0, True)), (k, 0, n)))
Example #2
0
def test_binomial_quantile():
    X = Binomial('X', 50, S.Half)
    assert quantile(X)(0.95) == S(31)

    X = Binomial('X', 5, S.Half)
    p = Symbol("p", positive=True)
    assert quantile(X)(p) == Piecewise((nan, p > S.One), (S.Zero, p <= Rational(1, 32)),\
        (S.One, p <= Rational(3, 16)), (S(2), p <= S.Half), (S(3), p <= Rational(13, 16)),\
        (S(4), p <= Rational(31, 32)), (S(5), p <= S.One))
Example #3
0
def test_binomial_quantile():
    X = Binomial('X', 50, S.Half)
    assert quantile(X)(0.95) == S(31)

    X = Binomial('X', 5, S(1) / 2)
    p = Symbol("p", positive=True)
    assert quantile(X)(p) == Piecewise((nan, p > S(1)), (S(0), p <= S(1)/32),\
        (S(1), p <= S(3)/16), (S(2), p <= S(1)/2), (S(3), p <= S(13)/16),\
        (S(4), p <= S(31)/32), (S(5), p <= S(1)))
Example #4
0
def test_binomial_symbolic():
    n = 10  # Because we're using for loops, can't do symbolic n
    p = symbols('p', positive=True)
    X = Binomial('X', n, p)
    assert simplify(E(X)) == n * p == simplify(moment(X, 1))
    assert simplify(variance(X)) == n * p * (1 - p) == simplify(cmoment(X, 2))
    assert cancel((skewness(X) - (1 - 2 * p) / sqrt(n * p * (1 - p)))) == 0

    # Test ability to change success/failure winnings
    H, T = symbols('H T')
    Y = Binomial('Y', n, p, succ=H, fail=T)
    assert simplify(E(Y) - (n * (H * p + T * (1 - p)))) == 0
Example #5
0
def test_binomial_symbolic():
    n = 10  # Because we're using for loops, can't do symbolic n
    p = symbols('p', positive=True)
    X = Binomial('X', n, p)
    assert Eq(simplify(E(X)), n * p)
    assert Eq(simplify(variance(X)), n * p * (1 - p))
    # Can't detect the equality
    #    assert Eq(simplify(skewness(X)), (1-2*p)/sqrt(n*p*(1-p)))

    # Test ability to change success/failure winnings
    H, T = symbols('H T')
    Y = Binomial('Y', n, p, succ=H, fail=T)
    assert Eq(simplify(E(Y)), simplify(n * (H * p + T * (1 - p))))
Example #6
0
def test_sample_scipy():
    distribs_scipy = [
        FiniteRV('F', {
            1: S.Half,
            2: Rational(1, 4),
            3: Rational(1, 4)
        }),
        DiscreteUniform("Y", list(range(5))),
        Die("D"),
        Bernoulli("Be", 0.3),
        Binomial("Bi", 5, 0.4),
        BetaBinomial("Bb", 2, 1, 1),
        Hypergeometric("H", 1, 1, 1),
        Rademacher("R")
    ]

    size = 3
    scipy = import_module('scipy')
    if not scipy:
        skip('Scipy not installed. Abort tests for _sample_scipy.')
    else:
        for X in distribs_scipy:
            samps = sample(X, size=size)
            samps2 = sample(X, size=(2, 2))
            for sam in samps:
                assert sam in X.pspace.domain.set
            for i in range(2):
                for j in range(2):
                    assert samps2[i][j] in X.pspace.domain.set
Example #7
0
def test_binomial_symbolic():
    n = 2  # Because we're using for loops, can't do symbolic n
    p = symbols('p', positive=True)
    X = Binomial('X', n, p)
    t = Symbol('t')

    assert simplify(E(X)) == n * p == simplify(moment(X, 1))
    assert simplify(variance(X)) == n * p * (1 - p) == simplify(cmoment(X, 2))
    assert cancel((skewness(X) - (1 - 2 * p) / sqrt(n * p * (1 - p)))) == 0
    assert characteristic_function(X)(t) == p**2 * exp(
        2 * I * t) + 2 * p * (-p + 1) * exp(I * t) + (-p + 1)**2

    # Test ability to change success/failure winnings
    H, T = symbols('H T')
    Y = Binomial('Y', n, p, succ=H, fail=T)
    assert simplify(E(Y) - (n * (H * p + T * (1 - p)))) == 0
Example #8
0
def test_factorial_moment():
    X = Poisson('X', 2)
    Y = Binomial('Y', 2, S.Half)
    Z = Hypergeometric('Z', 4, 2, 2)
    assert factorial_moment(X, 2) == 4
    assert factorial_moment(Y, 2) == S.Half
    assert factorial_moment(Z, 2) == Rational(1, 3)

    x, y, z, l = symbols('x y z l')
    Y = Binomial('Y', 2, y)
    Z = Hypergeometric('Z', 10, 2, 3)
    assert factorial_moment(Y, l) == y**2*FallingFactorial(
        2, l) + 2*y*(1 - y)*FallingFactorial(1, l) + (1 - y)**2*\
            FallingFactorial(0, l)
    assert factorial_moment(Z, l) == 7*FallingFactorial(0, l)/\
        15 + 7*FallingFactorial(1, l)/15 + FallingFactorial(2, l)/15
Example #9
0
def test_sample_scipy():
    distribs_scipy = [
        FiniteRV('F', {1: S.Half, 2: Rational(1, 4), 3: Rational(1, 4)}),
        DiscreteUniform("Y", list(range(5))),
        Die("D"),
        Bernoulli("Be", 0.3),
        Binomial("Bi", 5, 0.4),
        BetaBinomial("Bb", 2, 1, 1),
        Hypergeometric("H", 1, 1, 1),
        Rademacher("R")
    ]

    size = 3
    numsamples = 5
    scipy = import_module('scipy')
    if not scipy:
        skip('Scipy not installed. Abort tests for _sample_scipy.')
    else:
        with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
            h_sample = list(sample(Hypergeometric("H", 1, 1, 1), size=size, numsamples=numsamples))
            assert len(h_sample) == numsamples
            for X in distribs_scipy:
                samps = next(sample(X, size=size))
                samps2 = next(sample(X, size=(2, 2)))
                for sam in samps:
                    assert sam in X.pspace.domain.set
                for i in range(2):
                    for j in range(2):
                        assert samps2[i][j] in X.pspace.domain.set
Example #10
0
def main():
    # research
    # for x in range(430, 433):
    #     plot(x)
    # research conclude that when x >= 432, capital > 10**9

    x = 432
    bin_density = density(Binomial('X', 1000, S.Half)).dict
    prob = sum(bin_density[i] for i in range(x, 1001))
    print(prob.evalf(12))
Example #11
0
def test_issue_20286():
    n, p = symbols('n p')
    B = Binomial('B', n, p)
    k = Dummy('k', integer=True)
    eq = Sum(
        Piecewise(
            (-p**k * (1 - p)**(-k + n) *
             log(p**k * (1 - p)**(-k + n) * binomial(n, k)) * binomial(n, k),
             (k >= 0) & (k <= n)), (nan, True)), (k, 0, n))
    assert eq.dummy_eq(H(B))
Example #12
0
def test_factorial_moment():
    X = Poisson("X", 2)
    Y = Binomial("Y", 2, S.Half)
    Z = Hypergeometric("Z", 4, 2, 2)
    assert factorial_moment(X, 2) == 4
    assert factorial_moment(Y, 2) == S.Half
    assert factorial_moment(Z, 2) == Rational(1, 3)

    x, y, z, l = symbols("x y z l")
    Y = Binomial("Y", 2, y)
    Z = Hypergeometric("Z", 10, 2, 3)
    assert factorial_moment(Y, l) == y ** 2 * FallingFactorial(2, l) + 2 * y * (
        1 - y
    ) * FallingFactorial(1, l) + (1 - y) ** 2 * FallingFactorial(0, l)
    assert (
        factorial_moment(Z, l)
        == 7 * FallingFactorial(0, l) / 15
        + 7 * FallingFactorial(1, l) / 15
        + FallingFactorial(2, l) / 15
    )
Example #13
0
def test_bernoulli():
    p, a, b, t = symbols('p a b t')
    X = Bernoulli('B', p, a, b)

    assert E(X) == a * p + b * (-p + 1)
    assert density(X)[a] == p
    assert density(X)[b] == 1 - p
    assert characteristic_function(X)(
        t) == p * exp(I * a * t) + (-p + 1) * exp(I * b * t)
    assert moment_generating_function(X)(
        t) == p * exp(a * t) + (-p + 1) * exp(b * t)

    X = Bernoulli('B', p, 1, 0)
    z = Symbol("z")

    assert E(X) == p
    assert simplify(variance(X)) == p * (1 - p)
    assert E(a * X + b) == a * E(X) + b
    assert simplify(variance(a * X + b)) == simplify(a**2 * variance(X))
    assert quantile(X)(z) == Piecewise((nan, (z > 1) | (z < 0)),
                                       (0, z <= 1 - p), (1, z <= 1))
    Y = Bernoulli('Y', Rational(1, 2))
    assert median(Y) == FiniteSet(0, 1)
    Z = Bernoulli('Z', Rational(2, 3))
    assert median(Z) == FiniteSet(1)
    raises(ValueError, lambda: Bernoulli('B', 1.5))
    raises(ValueError, lambda: Bernoulli('B', -0.5))

    #issue 8248
    assert X.pspace.compute_expectation(1) == 1

    p = Rational(1, 5)
    X = Binomial('X', 5, p)
    Y = Binomial('Y', 7, 2 * p)
    Z = Binomial('Z', 9, 3 * p)
    assert coskewness(Y + Z, X + Y, X + Z).simplify() == 0
    assert coskewness(Y + 2*X + Z, X + 2*Y + Z, X + 2*Z + Y).simplify() == \
                        sqrt(1529)*Rational(12, 16819)
    assert coskewness(Y + 2*X + Z, X + 2*Y + Z, X + 2*Z + Y, X < 2).simplify() \
                        == -sqrt(357451121)*Rational(2812, 4646864573)
Example #14
0
def test_binomial_numeric():
    nvals = range(5)
    pvals = [0, S(1) / 4, S.Half, S(3) / 4, 1]

    for n in nvals:
        for p in pvals:
            X = Binomial('X', n, p)
            assert E(X) == n * p
            assert variance(X) == n * p * (1 - p)
            if n > 0 and 0 < p < 1:
                assert skewness(X) == (1 - 2 * p) / sqrt(n * p * (1 - p))
            for k in range(n + 1):
                assert P(Eq(X, k)) == binomial(n, k) * p**k * (1 - p)**(n - k)
Example #15
0
def test_sample_pymc3():
    distribs_pymc3 = [Bernoulli('B', 0.2), Binomial('N', 5, 0.4)]
    size = 3
    pymc3 = import_module('pymc3')
    if not pymc3:
        skip('PyMC3 is not installed. Abort tests for _sample_pymc3.')
    else:
        for X in distribs_pymc3:
            samps = sample(X, size=size, library='pymc3')
            for sam in samps:
                assert sam in X.pspace.domain.set
        raises(NotImplementedError, lambda:
               (sample(Die("D"), library='pymc3')))
Example #16
0
def test_sample_numpy():
    distribs_numpy = [Binomial("B", 5, 0.4), Hypergeometric("H", 2, 1, 1)]
    size = 3
    numpy = import_module('numpy')
    if not numpy:
        skip('Numpy is not installed. Abort tests for _sample_numpy.')
    else:
        for X in distribs_numpy:
            samps = sample(X, size=size, library='numpy')
            for sam in samps:
                assert sam in X.pspace.domain.set
        raises(NotImplementedError, lambda: sample(Die("D"), library='numpy'))
    raises(NotImplementedError,
           lambda: Die("D").pspace.sample(library='tensorflow'))
Example #17
0
def test_binomial_numeric():
    nvals = range(5)
    pvals = [0, S(1) / 4, S.Half, S(3) / 4, 1]

    for n in nvals:
        for p in pvals:
            X = Binomial(n, p)
            assert Eq(E(X), n * p)
            assert Eq(Var(X), n * p * (1 - p))
            if n > 0 and 0 < p < 1:
                assert Eq(Skewness(X), (1 - 2 * p) / sqrt(n * p * (1 - p)))
            for k in range(n + 1):
                assert Eq(P(Eq(X, k)),
                          binomial(n, k) * p**k * (1 - p)**(n - k))
Example #18
0
def test_binomial_numeric():
    nvals = range(5)
    pvals = [0, Rational(1, 4), S.Half, Rational(3, 4), 1]

    for n in nvals:
        for p in pvals:
            X = Binomial('X', n, p)
            assert E(X) == n*p
            assert variance(X) == n*p*(1 - p)
            if n > 0 and 0 < p < 1:
                assert skewness(X) == (1 - 2*p)/sqrt(n*p*(1 - p))
                assert kurtosis(X) == 3 + (1 - 6*p*(1 - p))/(n*p*(1 - p))
            for k in range(n + 1):
                assert P(Eq(X, k)) == binomial(n, k)*p**k*(1 - p)**(n - k)
Example #19
0
    def gen_samples(self, n, r, a=None, b=None):
        if not a: a = self.a
        if not b: b = self.b

        samples = np.empty((0, r))

        for _ in range(n):
            p = Beta('p', a, b)
            B = Binomial('B', 1, sym_sample(p))
            sample = []
            for _ in range(r):
                # TODO: change to sample a complete vector at once
                sample.append(sym_sample(B))
            samples = np.append(samples, [sample], axis=0)
        return samples
Example #20
0
def test_sample_pymc3():
    distribs_pymc3 = [Bernoulli('B', 0.2), Binomial('N', 5, 0.4)]
    size = 3
    pymc3 = import_module('pymc3')
    if not pymc3:
        skip('PyMC3 is not installed. Abort tests for _sample_pymc3.')
    else:
        with ignore_warnings(
                UserWarning
        ):  ### TODO: Restore tests once warnings are removed
            for X in distribs_pymc3:
                samps = next(sample(X, size=size, library='pymc3'))
                for sam in samps:
                    assert sam in X.pspace.domain.set
            raises(NotImplementedError,
                   lambda: next(sample(Die("D"), library='pymc3')))
Example #21
0
def test_sample_numpy():
    distribs_numpy = [
        Binomial("B", 5, 0.4),
    ]
    size = 3
    numpy = import_module('numpy')
    if not numpy:
        skip('Numpy is not installed. Abort tests for _sample_numpy.')
    else:
        with ignore_warnings(UserWarning):
            for X in distribs_numpy:
                samps = next(sample(X, size=size, library='numpy'))
                for sam in samps:
                    assert sam in X.pspace.domain.set
            raises(NotImplementedError,
                lambda: next(sample(Die("D"), library='numpy')))
    raises(NotImplementedError,
            lambda: Die("D").pspace.sample(library='tensorflow'))
Example #22
0
def test_binomial_verify_parameters():
    raises(ValueError, lambda: Binomial('b', .2, .5))
    raises(ValueError, lambda: Binomial('b', 3, 1.5))
Example #23
0
def test_binomial_verify_parameters():
    raises(ValueError, lambda: Binomial("b", 0.2, 0.5))
    raises(ValueError, lambda: Binomial("b", 3, 1.5))
def rouwenhorst_initial_distribution(rho, sigma, ns):
    p = (1 + rho) / 2
    q = p
    s = (1 - p) / (2 - (p + q))
    return list(density(Binomial('x', ns - 1, s)).dict.values())