Skip to content

Instantly share code, notes, and snippets.

@magsol
Last active December 15, 2015 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magsol/5170687 to your computer and use it in GitHub Desktop.
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).
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