Last active
December 15, 2015 00:09
-
-
Save magsol/5170687 to your computer and use it in GitHub Desktop.
Demonstrates how to sample from exponential and gaussian distributions using only a uniform distribution (useful for languages like PHP with no built-in statistical sampling libraries).
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
import numpy as np | |
import matplotlib.pyplot as plot | |
import sys | |
def exp(mean, samples = 100): | |
y = [] | |
lambda_param = (1 / mean) | |
for i in range(0, samples): | |
rand = np.random.rand() | |
y.append(np.log(1 - rand) / (-1.0 * lambda_param)) | |
plot.hist(y, bins = 100) | |
plot.show() | |
def normal(mean = 0, stddev = 1, samples = 100): | |
y = [] | |
for i in range(0, samples): | |
rand1 = np.random.rand() | |
rand2 = np.random.rand() | |
var = np.sqrt(-2 * np.log(rand1)) * np.cos(2 * np.pi * rand2) | |
y.append((var * stddev) + mean) | |
plot.hist(y, bins = 100) | |
plot.show() | |
normal(mean = 40, stddev = 1, samples = 10000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment