Добавил:
yurochka
Периодически делаю учебные работы по предметам ЛЭТИ и выгружаю их сюда для пополнения базы, с которой можно будет свериться.
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Лабораторная 1 / Метод середины квадратов / Lab1
.pyimport matplotlib.pyplot as plt
import numpy as np
class MyRandom:
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
def check_period(self):
seen = {}
x = self.seed
period = 0
while x not in seen:
seen[x] = period
x = int(str(x**2).zfill(2*self.length)
[self.length//2:self.length//2+self.length])
period += 1
return period
rand = MyRandom(11111111)
print(rand.check_period())
rand_list = []
for i in range(10000):
rand_list.append(rand.next())
N = len(rand_list)
M = sum(rand_list) / N
D = (sum(z * z for z in rand_list) - (M * M) * N) / N
print(f"Моменты: M = {M}; D = {D}")
base = np.linspace(0, 1, N)
plt.hist([rand_list, base],
bins=10,
weights=[np.ones_like(rand_list) / len(rand_list),
np.ones_like(base) / base.size],
label=['Эмпирическое', 'Теоретическое'])
plt.legend(loc='upper right')
plt.savefig("Yulia/ms1.1.svg")
plt.show()
S_list = (2, 5, 10)
for S in S_list:
targetNs = [x*200 for x in range(1, 30)]
Rs = []
for targetN in targetNs:
rand = MyRandom(11111111)
rand_list.clear()
for k in range(targetN):
rand_list.append(rand.next())
N = len(rand_list)
randX = rand_list[:N-S]
randY = rand_list[S:]
R = np.corrcoef(randX, randY)[0, 1]
Rs.append(R)
if S == S_list[0]:
plt.plot(targetNs, Rs, color='r', label='s = 2')
if S == S_list[1]:
plt.plot(targetNs, Rs, color='b', label='s = 5')
if S == S_list[2]:
plt.plot(targetNs, Rs, color='g', label='s = 10')
plt.title("Коэффициент корреляции при s = 2, 5, 10")
plt.legend()
plt.xlabel("N")
plt.ylabel("R")
plt.grid(True)
plt.axhline(y=0, color='k')
plt.axvline(x=0, color='k')
plt.savefig("Yulia/ms1.s.svg")
plt.show()
Соседние файлы в папке Метод середины квадратов
