User:Eliezer Yudkowsky/CodeDump

From LessWrong
Jump to navigation Jump to search

Runs on Python 3, Python 2 seems to have problems probably owing to longints not being standard.

Damn ugly stuff written in a hurry, no comments, no docs, slow, wrote things I could write faster than looking them up, etc.

Bayes version:

import random

kSize = 500

samples = 10000
bayesfactor = 20
alternative = 0.55
successCount = [0] * kSize

def like(m, n): return ((alternative / 0.5)**m)*(((1-alternative)/0.5)**(n-m))

for s in range(samples):
    coins = 0
    for t in range(kSize):
        coins += random.randint(0, 1)
        if like(coins, t) > bayesfactor:
            successCount[t] += 1
            break
 
print (sum(successCount))

Frequentist version:

import random

kSize = 500
kStat = [[]] * (kSize+1)

samples = 10000
alpha = 0.05
successCount = [0] * kSize

facts = [1] * (kSize + 2)
for i in range(1, kSize + 2):
    facts[i] = i*facts[i-1]

def choose(m, n): return facts[n] // (facts[m]*facts[n-m])

for i in range(1, kSize+1):
    kStat[i] = [0] * (i+1)
    for j in range(0, i+1):
        kStat[i][j] = choose(j, i) / 2**i
    cuml = 0.0
    for j in range(0, i+1):
        cuml += kStat[i][j]
        kStat[i][j] = cuml
    if cuml < 0.99:
        print (cuml, i)
        raise "aargh"

for s in range(samples):
    coins = 0
    for t in range(kSize):
        coins += random.randint(0, 1)
        if kStat[t+1][coins] < alpha:
            successCount[t] += 1
            break
 
print (sum(successCount))