# Gambler's Fallacy dice import random import math import sys RATE = 300 FIRST = 3 RAND = 0.2 NUMFREQ = [1,2,3,4,5,6,5,4,3,2,1] # length 11 def random_fromweight(weight_list, choices): '''Given a list of weights 'weight_list' corresponding to the choices in 'choices', choose an element from 'choices' at random according to the weights in 'weight_list'.''' normalized_weight = [float(j)/sum(weight_list) for j in weight_list] # normalize the weights so they sum to 1 num = random.random() sumweights = 0 for i in range(len(weight_list)): sumweights += normalized_weight[i] if num <= sumweights: return choices[i] def new_weights(freq, rate=RATE): '''Compute the weights for the next roll, given the current frequency of rolls 'freq'.''' if sum(freq) == 0: return [0]*11 # constant array of zeros return [2**(rate*(float(NUMFREQ[j])/sum(NUMFREQ) - \ float(freq[j])/sum(freq))) for j in range(len(NUMFREQ))] def random_roll(): '''Roll two dice randomly. Return dice roll result.''' return random_fromweight(NUMFREQ,range(2,13)) def dice_roll(counter, freq, rand_prob=RAND, first=FIRST, rate=RATE): '''Roll the dice, return (dice roll, "string random/weighted"). Update 'freq.''' if counter <= first or random_fromweight([rand_prob,1-rand_prob],[1,0]): # then roll randomly roll = random_roll() rando = "Random" else: roll = random_fromweight(new_weights(freq, rate), range(2,13)) rando = "Weighted history" freq[roll-2] += 1 # increment current frequency return (roll, rando) def main(rand_prob=RAND, first=FIRST, rate=RATE): '''Main function to run Gambler's Fallacy dice.''' counter = 1 cur_freq = [0]*11 while 1: this_roll = dice_roll(counter, cur_freq) raw_input(str(this_roll[0])) #+ str(this_roll[1])) counter += 1 #def usage(): # print 'usage: python [-tlf] [length] %s file.tex' % sys.argv[0] # sys.exit(1) if __name__ == '__main__': main() #try: # main(sys.argv[1]) #except: #print sys.argv #usage()