Created
April 20, 2017 13:32
-
-
Save galtsev/0e43f0f709ead437503ee8db90fc3879 to your computer and use it in GitHub Desktop.
generate geometrically distributed numbers from uniformly distributed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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