dimanche 10 juillet 2016

Simulating a coin flip experiment in Python

I am having trouble getting a program to work properly. The goal is to simulate a coin flip as follows:

Consider a random sequence of numbers: epsilon_1, epsilon_2, ... , epsilon_N. Each term in this sequence takes on values +1 or -1, depending on the outcome of the coin toss experiment, heads or tails respectively.

In other words, for each n = 1,2,...,N:

epsilon_n = { +1 with probability = 1/2; and -1 with probability = 1/2.

Now, I wrote some psuedo-code to help me write this program:

# for n = 1,2,...,N:
# flip coin
# if result == "Heads"
    # epsilon_{n} = 1
# else:
    # epsilon_{n} = -1

I want to store the values of epsilon for each n (and hence, the result of the experiment for each n) in an array. Here is the program I wrote which hoped to accomplish this:

    # array to store outcome of the coin flip
epsilon = np.zeros(N)

# define coin flip experiment
result = [] # result of the experiment
for n in xrange(1, N):
    def coin_flip(): #flip coin for each n = 1,...,N
        flip = random.randint(0,2) 
        if (flip == 0):
            result = "Heads"
        else:
            result = "Tails"
        return result
    if result == "Heads":
        epsilon[n] = 1
    else:
        epsilon[n] = -1

print epsilon

The output of this program is an array with the first entry being 0, and all other entries contain the value -1. I specified N = 100.

Please, some guidance is all I require. For instance, I think I am on the right track with defining a function for the coin toss experiment. I need it to return the result of the experiment (Heads or Tails), and this need to happen for each n = 0,1,...,N but I am unsure of the best method to do so. Then for the result of each individual coin flip, my program must store the value +1 or -1 in the array for epsilon. Must I include n as a parameter for my proposed function?? Am I on the right track here?

Any and all help is very greatly appreciated. Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire