2016-03-08 78 views
0

這是我第一次寫一個隨機數發生器,我只是亂搞,看看我能用隨機公式來做什麼。我寫了一個簡單的隨機數發生器,我如何繪製我寫的函數的分佈?

但是,我很好奇,我的功能是如何偏見,並與功能的分佈(1至9之間)。 這裏是我的不必要的長碼:

import time 

class Random: 
    """random generator""" 

    def __init__(self): 
     """ Random()-> create a random number generator with a random seed 
     a seed is needed in order to generate random numbers""" 
     self.seed = time.time() 

    def random(self): 
     """ Random.random() -> get a random number using a formula""" 
     self.seed =(((int(self.seed)*129381249123+2019383)**0.74123)/517247) % 288371 

    def get_ran_num(self): 
     """ Random.get_ran_num() -> return a random integer from 1 thru 10""" 
     self.random() 
     return int(list(str(int(self.seed)))[3]) 


ranNum = Random() 

,如果存在一些工具,可以採取隨機函數,然後運行它幾千次,然後繪製它的分佈這將是巨大的。

預先感謝您

P/S:我怎樣才能提高我的RNG,並使其更隨機呃?

+0

使用PyPlot :) http://matplotlib.org/users/pyplot_tutorial.html – Goodies

回答

1

如果你只是想要一個可視化表示,可以很容易地使用

import matplotlib.pyplot as plt 
# Random class here 
ranNum = Random() 
randNums = [ranNum.get_ran_num() for _ in range(100)] 
nums = list(range(len(randNums))) 
plt.plot(nums, randNums, 'ro') 
plt.show() 

這是對100枚隨機數: https://i.gyazo.com/bd3f11fb80de18797dc888138d5e5113.png

不過,我發現了一個IndexError當我去更高的範圍。你或許應該解決實際算法,無論是導致該問題,但我把創可貼上的方式是:

def get_ran_num(self): 
    """ Random.get_ran_num() -> return a random integer from 1 thru 10""" 
    retval = None 
    while True: 
     try: 
      self.random() 
      retval = int(list(str(int(self.seed)))[3]) 
      break 
     except IndexError as e: 
      continue 
    return retval 

下面是100,000個隨機數,這是非常好的一個情節。相互連接的線條比沒有明顯比其他線條更密集的是你所追求的,但是你需要做更好的熵分析來發現比快速視覺表示更有用的東西。就你而言,它看起來像6更受青睞。此外,它看起來像經常重複。

enter image description here

1

我會嘗試random.rand和matplotlib。

import numpy as np 
import matplotlib.pyplot as plt 


N = 50 
x = np.random.rand(N) 
y = np.random.rand(N) 
colors = np.random.rand(N) 
area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses 

plt.scatter(x, y, s=area, c=colors, alpha=0.5) 
plt.show() 

是這樣的嗎?

編輯:你是否想要生成僞隨機數?無論如何,你需要一個移位寄存器的種子,所以在這方面,我不確定它是否是完全隨機的。

0

我寧願直方圖來檢查你的隨機數生成器的分佈的均勻性。

import numpy as np 
import matplotlib 
import matplotlib.pyplot as plt 
myarr = np.random.randint(1000, size=100000) 
plt.hist(myarr, bins=40) 
plt.show() 

enter image description here

相關問題