BERKYT

Custom random on python

Dec 17th, 2021 (edited)
1,110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | None | 0 0
  1. import random as rnd
  2. import time
  3. import os
  4. from matplotlib import pyplot as plt
  5.  
  6.  
  7. def lcg(seed, n, r):
  8.     m = 2**31
  9.     a = 1103515245
  10.     c = 12345
  11.  
  12.     nums = []
  13.     indicies = []
  14.  
  15.     x = seed
  16.  
  17.     for i in range(n):
  18.         x = (a * x + c) % m
  19.  
  20.         nums.append(x % r)
  21.         indicies.append(i)
  22.  
  23.     return nums, indicies
  24.  
  25.  
  26. def random(seed, n, r):
  27.     nums = []
  28.     indicies = []
  29.     rnd.seed(seed)
  30.  
  31.     for i in range(n):
  32.         x = rnd.randint(0, r)
  33.  
  34.         nums.append(x)
  35.         indicies.append(i)
  36.  
  37.     return nums, indicies
  38.  
  39.  
  40. if __name__ == "__main__":
  41.     print("Enter N (amount of numbers)")
  42.     n = int(input())
  43.  
  44.     print("Enter R (maximum possible number)")
  45.     r = int(input())
  46.  
  47.     seed = time.time()
  48.  
  49.     lcg_nums, lcg_indicies = lcg(seed, n, r)
  50.     random_nums, random_indicies = random(seed, n, r)
  51.  
  52.     fig = plt.figure(figsize=(20, 10))
  53.  
  54.     lcg_plot = fig.add_subplot(1, 2, 1)
  55.     lcg_plot.set_title("linear congruential generator")
  56.     lcg_plot.scatter(lcg_indicies, lcg_nums)
  57.  
  58.     random_plot = fig.add_subplot(1, 2, 2)
  59.     random_plot.set_title("built-in random")
  60.     random_plot.scatter(random_indicies, random_nums)
  61.  
  62.     fig_path = os.path.join(os.path.dirname(__file__), 'rnd.png')
  63.     fig.savefig(fig_path)
  64.     print("Saved result as {}".format(fig_path))
  65.  
Add Comment
Please, Sign In to add comment