Skip to content

Commit 9c64f79

Browse files
committed
Adding the New Metropolis_Hasting Algorithm
1 parent 1b296aa commit 9c64f79

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import numpy as np
2+
3+
def metropolis_hastings(target_distribution, proposal_distribution, num_samples, initial_state):
4+
samples = [initial_state]
5+
current_state = initial_state
6+
7+
for _ in range(num_samples):
8+
proposed_state = proposal_distribution(current_state)
9+
acceptance_ratio = min(1, target_distribution(proposed_state) / target_distribution(current_state))
10+
11+
if np.random.rand() < acceptance_ratio:
12+
current_state = proposed_state
13+
14+
samples.append(current_state)
15+
16+
return samples[1:]
17+
18+
def target_distribution(x):
19+
return np.exp(-x**2 / 2) / np.sqrt(2 * np.pi)
20+
21+
def proposal_distribution(x):
22+
return x + np.random.normal(0, 1)
23+
24+
if __name__ == "__main__":
25+
num_samples = 10000
26+
initial_state = 0
27+
28+
samples = metropolis_hastings(target_distribution, proposal_distribution, num_samples, initial_state)

0 commit comments

Comments
 (0)