2016-03-08 72 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

相关问题