P
P
Proshka172019-02-14 23:02:55
Probability theory
Proshka17, 2019-02-14 23:02:55

Programming challenge?

Good afternoon! I can't figure out how to solve the following programming problem:

Write a program that from a random Bernoulli variable with p = q = 0.5 and simple
mathematical operations one could obtain a random Bernoulli variable with
any given p ∈ [0,1].

The problem is not in the implementation (I have not reached it yet), but in how to represent the probability distribution in a programming language?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
longclaps, 2019-02-15
@longclaps

Heh, the bunny burns ))

from random import randint

def coin():
    """ реализация случайной бернуллиевской величины с p = q = 0.5 """
    return randint(0, 1)

def bernoulli(p):
    r = 0.
    for _ in range(53):  # магическое число обусловлено разрядностью типа float
                         # https://ru.wikipedia.org/wiki/Число_двойной_точности
        if coin():  # тут должен быть быть источник случайной величины из условия,
                    # например итератор по списку случайных нулей и единиц
            r += 1.
        r *= .5
    return int(r < p)

n, p = 10 ** 5, 1 / 3
print(sum(bernoulli(p) for _ in range(n)) / n)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question