官术网_书友最值得收藏!

Python random numbers in Jupyter

For many analyses, we are interested in calculating repeatable results. However, much of this analysis relies on some random numbers being used. In Python, you can set seed for the random number generator to achieve repeatable results with the random.seed() function.

In this example, we simulate rolling a pair of dice and look at the outcome. We would expect the average total of the two dice to be six, which is the half-way point between the faces.

The script we are using is as follows:

# using pylab statistics and histogram
import pylab
import random

# set random seed so we can reproduce results
random.seed(113)
samples = 1000

# declare our dataset store
dice = []

# generate and save the samples
for i in range(samples):
total = random.randint(1,6) + random.randint(1,6)
dice.append(total)

# compute some statistics on the dice throws
print("Throw two dice", samples, "times.")
print("Mean of", pylab.mean(dice))
print("Median of", pylab.median(dice))
print("Std Dev of", pylab.std(dice))

# display a histogram of the results
pylab.hist(dice, bins= pylab.arange(1.5,12.6,1.0))
pylab.xlabel("Pips")
pylab.ylabel("Count")
pylab.show()

Once we have the script in Jupyter and execute it, we will get the following result:

I added some more statistics. I'm not sure that I would have counted on such a high standard deviation. If we increased the number of samples, this would decrease.

The resulting graph was opened in a new window, much as it would if you ran this script in another Python development environment:

The graphic looks a little more jagged than I would have expected for a thousand samples.

主站蜘蛛池模板: 乌苏市| 新昌县| 吴桥县| 偏关县| 华坪县| 泽普县| 松阳县| 萨迦县| 汉寿县| 建水县| 万山特区| 浦城县| 上杭县| 建瓯市| 高平市| 秦皇岛市| 迁安市| 安国市| 丰镇市| 彩票| 金溪县| 江源县| 朔州市| 新龙县| 嘉定区| 临潭县| 弥勒县| 赣州市| 沙河市| 礼泉县| 福安市| 兴安县| 阿巴嘎旗| 石渠县| 安新县| 玉屏| 苍梧县| 贵德县| 增城市| 富川| 泰顺县|