Добавил:
yurochka
Периодически делаю учебные работы по предметам ЛЭТИ и выгружаю их сюда для пополнения базы, с которой можно будет свериться.
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Лабораторная 2 / Вариант 7 / Lab2
.pyimport matplotlib.pyplot as plt
import numpy as np
class MiddleSquareRandom:
def __init__(self, seed):
self.seed = seed
self.Aprev = seed
self.length = len(str(seed))
def next(self):
x = int(str(self.Aprev**2).zfill(2*self.length)
[self.length//2:self.length//2+self.length])
self.Aprev = x
return x / 10**self.length
class RandomValue:
def __init__(self, xj, pj):
self.Pj = [sum(pj[:i+1]) for i in range(len(pj))]
self.xj = xj
self.pj = pj
self.z = MiddleSquareRandom(11111111)
def next(self):
z = self.z.next()
for p in range(len(self.Pj)):
if z <= self.Pj[p]:
return self.xj[p]
x = np.array([-40.1, -12.9, -8.8, -3.6, 7.4, 37.2, 59.1])
p = [0.128, 0.157, 0.185, 0.014, 0.217, 0.056, 0.243]
rv = RandomValue(x, p)
RV = []
N = 500
for i in range(N):
RV.append(rv.next())
print("Первые 30 значений:")
for i in range(30):
print(RV[i])
M = sum(RV) / N
D = sum([x ** 2 for x in RV]) / N - M ** 2
print(f"Эмпирические: M = {M:.5f}, D = {D:.5f}")
M_exp = sum([p[j] * x[j] for j in range(len(p))])
D_exp = sum([p[j] * x[j] ** 2 for j in range(len(p))]) - M_exp ** 2
print(f"Теоретические: M = {M_exp:.5f}, D = {D_exp:.5f}")
edges = (x[:-1] + x[1:]) / 2
bins = np.concatenate(
([x[0] - (edges[0] - x[0])], edges, [x[-1] + (x[-1] - edges[-1])]))
plt.hist([RV, x], bins=bins,
weights=[np.ones_like(RV) / len(RV), np.ones_like(x) * p],
label=['Эмпирическое', 'Теоретическое'])
plt.legend(loc='upper left')
plt.savefig("Yulia/ms2.svg")
plt.show()
