Skip to content

Instantly share code, notes, and snippets.

@galtsev
Created April 20, 2017 13:32
Show Gist options
  • Select an option

  • Save galtsev/0e43f0f709ead437503ee8db90fc3879 to your computer and use it in GitHub Desktop.

Select an option

Save galtsev/0e43f0f709ead437503ee8db90fc3879 to your computer and use it in GitHub Desktop.
generate geometrically distributed numbers from uniformly distributed
# https://math.stackexchange.com/questions/485448/prove-the-way-to-generate-geometrically-distributed-random-numbers
import math
import random
N = 100
M = 1000000
p = 0.1 #use 0.01 for actual distribution
def expected():
res = []
rem = 1.0
for i in range(N):
v = rem*p
res.append(int(v*M))
rem -= v
return res
def gen()
def calc():
res = [0 for i in range(N)]
pp = 1/math.log(1-p)
for i in range(M):
n = int(pp*math.log(random.random()))
if n<N:
res[n]+=1
return res
print(expected())
print(calc())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment