-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprml_11_3.py
More file actions
78 lines (57 loc) · 1.59 KB
/
prml_11_3.py
File metadata and controls
78 lines (57 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 17 22:54:08 2017
@author: Narifumi
"""
import numpy as np
import matplotlib.pyplot as plt
def dist_exp(y, lam):
py = lam * np.exp(-lam * y)
return py
def rand_exp(N, lam):
z = np.random.rand(N)
y = -np.log(1 - z) / lam
return y
def dist_cauchy(y):
py = 1 / (np.pi * (1 + y**2))
return py
def rand_cauchy(N):
z = np.random.rand(N)
y = np.tan(np.pi * (z - 0.5))
return y
def dist_gauss(y):
py = np.exp(-0.5 * (y**2)) / np.sqrt(2 * np.pi)
return py
def rand_gauss(N):
z = np.random.rand(2, N) * 2 - 1
for i in range(N):
while(z[0, i]**2 + z[1, i]**2 > 1):
z[:, i] = np.random.rand(2) * 2 - 1
r2 = z[0, :]**2 + z[1, :]**2
y = np.zeros([2, N])
y[0, :] = z[0, :] * (-2 * np.log(r2) / r2)**0.5
y[1, :] = z[1, :] * (-2 * np.log(r2) / r2)**0.5
return y
N = 100000
xMax = 5
bins = 200
plt.subplot(2, 2, 1)
plt.xlim([0, xMax])
x = np.linspace(0, xMax, 1000)
lam = 1
plt.plot(x, dist_exp(x, lam), 'r')
plt.hist(rand_exp(N, lam), bins=bins, range=[0, 5 * xMax], density=True, alpha=0.2)
plt.subplot(2, 2, 2)
plt.xlim([-xMax, xMax])
x = np.linspace(-xMax, xMax, 1000)
plt.plot(x, dist_cauchy(x), 'r')
plt.hist(rand_cauchy(N), bins=bins, range=[-5 * xMax, 5 * xMax], density=True, alpha=0.2)
plt.subplot(2, 2, 3)
plt.xlim([-xMax, xMax])
x = np.linspace(-xMax, xMax, 1000)
y = rand_gauss(N)
plt.plot(x, dist_gauss(x), 'r')
plt.hist(y[0, :], bins=bins, range=[-5 * xMax, 5 * xMax], density=True, alpha=0.2)
# plt.hist2d(y[0,:],y[1,:],bins=50)
plt.show()