• API
• FAQ
• Tools
• Archive
SHARE
TWEET # randtest KrimsN  May 29th, 2020 (edited) 469 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. import random
2. import time
3. import matplotlib.pyplot as plt
4. import numpy as np
5. from hist import build_hist
6.
7.
8. class MyPRNG:
9.     b = 5.65465463546133
10.     def __init__(self, seed=None):
11.         # timestamp
12.         s = seed if seed is not None else time.time()
13.         self.z = s-int(s)
14.
15.     def foo(self):
16.         x = 3**(self.z+MyPRNG.b)
17.         return x-int(x)
18.
19.     def __call__(self):
20.         self.z = self.foo()
21.         return self.z
22.
23.
24. def sample(rand, n):
25.     return [rand() for i in range(n)]
26.
27. def expval(X):
28.     return sum(X) / len(X)
29.
30. def disp(X, M):
31.     return sum((x-M)**2 for x in X) / (len(X)-1)
32.
33.
34. if __name__ == "__main__":
35.     real_M = 0.5
36.     real_D = 1/12
37.     size = 10**6
38.
39.     bars = 20
40.     random.seed()
41.     S1 = sample(random.random, size)
42.     G1 = build_hist(S1, bars)
43.     M = expval(S1)
44.     D = np.var(S1)
45.
46.     print(f'random.random| M: {M}, D: {D}')
47.     print(f'random.random| errors: M: {abs(real_M-M)/real_M}, D: {abs(real_D-D)/real_D}')
48.
49.     R = MyPRNG()
50.     S2 = sample(R, size)
51.     G2 = build_hist(S2, bars)
52.     M = expval(S2)
53.     D = np.var(S2)
54.
55.     print(f'My| M: {M}, D: {D}')
56.     print(f'My| errors: M: {abs(real_M-M)/real_M}, D: {abs(real_D-D)/real_D}')
57.
58.     # plt.style.use('dark_background')
59.     plt.style.use('seaborn-dark')
60.     fig, ax = plt.subplots()
61.     plt.ylim(ymax = 0.06, ymin = 0)
62.     x_axis = [f'{i/bars:.2f}' for i in range(bars)]
63.
64.     x = np.arange(bars)
65.     width = 0.37
66.     rects1 = ax.bar(x - width/2, G1, width, label='random.random')
67.     rects2 = ax.bar(x + width/2, G2, width, label='My' )
68.     ax.set_title('Сравнение функций распределения')
69.     ax.set_xticks(x)
70.
71.     ax.set_ylabel('p')
72.     ax.set_xticklabels(x_axis)
73.     ax.legend()
74.     plt.show()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.
Top