我正在尝试使用 Python 中的类来模拟马尔可夫链。这是我的代码:
import random
...
class Chain:
def __init__(self, probabilities, start):
self.probs = probabilities
self.start = start
self.names = list(self.probs.keys())
def __iter__(self):
self.pos = self.start
return self
def __next__(self):
self.random_num = random.randrange(100)
prob_l = self.probs[self.pos]
for ind, prob in enumerate(prob_l):
self.prob_sum += prob
if self.random_num < self.prob_sum:
exclude_names = self.names[:ind] + self.names[ind + 1 :]
self.prob_sum = 0
self.pos = exclude_names[ind]
return self.pos
return self.pos
chain = Chain({"A": [50, 25], "B": [50, 25], "C": [50, 50]}, "A")
chain_iter = iter(chain)
for k in range(100):
print(next(chain_iter))
它按预期工作,但有时会重复字母 C。由于字典中的两个 50,它应该有 50/50 的机会转到 A 或 B。它不应该重复。
DIEA
相关分类