# CS 237 Spring 2019
# Author: Alina Ene (aene@bu.edu)
from numpy.random import uniform
import numpy as np # arrays and functions which operate on array
import matplotlib.pyplot as plt # normal plotting
from collections import Counter
plt.style.use('seaborn') # pretty plots
from ipywidgets import interact
The following functions allow us to sample uniformly from intervals and 2D regions such as squares and disks.
# uniform sampling from [0, 1]
def uniform_unit_interval():
x = uniform(0, 1)
return x
# uniform sampling from [a, b]
def uniform_interval(a, b):
x = uniform(a, b)
return x
print(uniform_interval(0, 1))
0.206633651527671
print(uniform_interval(-6, 10))
-3.8309404315070097
# uniform sampling from unit square [0, 1]x[0, 1]
def uniform_unit_square():
x = uniform(0, 1)
y = uniform(0, 1)
return (x, y)
# uniform sampling from the rectangle [a, b]x[c, d]
def uniform_rectangle(a, b, c, d):
x = uniform(a, b)
y = uniform(c, d)
return (x, y)
print(uniform_unit_square())
(0.5115668623722053, 0.5640717487354029)
# uniform sampling from a unit disk centered at (0, 0)
def uniform_unit_disk():
while True:
# sample from the square
(x, y) = uniform_rectangle(-1, 1, -1, 1)
# check if (x, y) is on the disk
if x**2 + y**2 <= 1:
return (x, y)
print(uniform_unit_disk())
(-0.39883557761001764, -0.2630760599589246)
def uniform_square_plot(n_trials):
x_vals = uniform(0,1,[n_trials])
y_vals = uniform(0,1,[n_trials])
plt.figure(num=None, figsize=(8, 8), dpi=89)
plt.scatter(x_vals, y_vals, marker='x', c='blue')
plt.show()
uniform_square_plot(10000)
# plots a dart board of radius r centered at (0, 0)
def plot_dart_board(r = 1):
pi_vals = np.arange(0, 1.01, .01) * 2 * np.pi
x = r * np.cos(pi_vals)
y = r * np.sin(pi_vals)
# Plot board
plt.figure(figsize=(8,8))
plt.plot(x,y)
plt.title("Throwing Darts at a Dart Board", fontsize = 15)
# Plot bullzeye
plt.scatter(0,0,marker='x', c='red')
def throw_darts(n_darts = 10):
#plt.figure(figsize=(8,8))
plot_dart_board()
x = []
y = []
for i in range(n_darts):
(a, b) = uniform_unit_disk()
x.append(a)
y.append(b)
plt.scatter(x,y, alpha=.5, marker='x', c='blue')
plt.show()
throw_darts(10000)
#interact(throw_darts, n_darts = (1,10000))