Добавил:
Периодически делаю учебные работы по предметам ЛЭТИ и выгружаю их сюда для пополнения базы, с которой можно будет свериться. Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Скачиваний:
0
Добавлен:
11.01.2026
Размер:
1.98 Кб
Скачать
import matplotlib.pyplot as plt
import numpy as np
import random


a = []
s = []
for _ in range(55):
    a.append(random.randint(0, 2**32))
for _ in range(52):
    s.append(random.randint(0, 2**32))

I = {'a': 54, 's': 51}


def next_a():
    I['a'] += 1
    a[I['a'] % 55] = (a[(I['a'] - 55) % 55] + a[(I['a'] - 24) % 55]) % 2**32
    return a[I['a'] % 55]


def next_s():
    I['s'] += 1
    a[I['s'] % 52] = (a[(I['s'] - 52) % 52] + a[(I['s'] - 19) % 52]) % 2**32
    return a[I['s'] % 52]


def next_z():
    z0 = next_a()
    z1 = next_s()
    while z1 & 1 != 1:
        z0 = next_a()
        z1 = next_s()
    return z0 / 2 ** 32, z1 / 2 ** 32


class Random:
    def __init__(self, xj, pj):
        self.Pj = [sum(pj[:i+1]) for i in range(len(pj))]
        self.xj = xj
        self.pj = pj

    def next(self):
        z = next_z()[0]
        for p in range(len(self.Pj)):
            if z <= self.Pj[p]:
                return self.xj[p]


x = np.array([-48.6, -34.1, -31.9, -16.5, -15.8, 21.2, 38.6])
p = [0.195, 0.089, 0.020, 0.139, 0.198, 0.244, 0.115]
rv = Random(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("Yura/ms2.svg")
plt.show()
Соседние файлы в папке Вариант 14