返回介绍

Random numbers

发布于 2025-02-25 23:43:39 字数 3217 浏览 0 评论 0 收藏 0

There are two modules for (pseudo) random numbers that are commonly used. When all you need is to generate random numbers from some distribtuion, the numpy.random moodule is the simplest to use. When you need more information realted to a disttribution such as quantiles or the PDF, you can use the scipy.stats module.

Module Reference

import numpy.random as npr
npr.seed(123) # fix seed for reproducible results
# 10 trials of rolling a fair 6-sided 100 times
roll = 1.0/6
x = npr.multinomial(100, [roll]*6, 10)
x
array([[18, 14, 14, 18, 20, 16],
       [16, 25, 16, 14, 14, 15],
       [15, 19, 16, 12, 18, 20],
       [19, 13, 14, 18, 18, 18],
       [18, 20, 17, 16, 16, 13],
       [15, 16, 15, 16, 20, 18],
       [12, 17, 17, 18, 17, 19],
       [15, 16, 22, 21, 13, 13],
       [18, 12, 16, 17, 22, 15],
       [14, 17, 25, 15, 15, 14]])
# uniformly distributed numbers in 2D
x = npr.uniform(-1, 1, (100, 2))
plt.scatter(x[:,0], x[:,1], s=50)
plt.axis([-1.05, 1.05, -1.05, 1.05]);

# ranodmly shuffling a vector
x = np.arange(10)
npr.shuffle(x)
x
array([5, 8, 6, 4, 3, 9, 1, 7, 2, 0])
# radnom permutations
npr.permutation(10)
array([1, 4, 9, 8, 6, 5, 3, 2, 0, 7])
# radnom selection without replacement
x = np.arange(10,20)
npr.choice(x, 10, replace=False)
array([14, 16, 15, 12, 19, 11, 13, 10, 18, 17])
# radnom selection with replacement
npr.choice(x, (5, 10), replace=True) # this is default
array([[15, 13, 10, 14, 18, 14, 19, 13, 15, 11],
       [18, 10, 19, 11, 15, 18, 18, 14, 16, 18],
       [17, 19, 12, 10, 10, 19, 19, 15, 13, 15],
       [15, 12, 12, 17, 13, 11, 13, 19, 13, 16],
       [12, 13, 11, 19, 18, 10, 12, 13, 17, 19]])
# toy example - estimating pi inefficiently
n = 1e6
x = npr.uniform(-1,1,(n,2))
4.0*np.sum(x[:,0]**2 + x[:,1]**2 < 1)/n
3.1416

Module refernce

import scipy.stats as stats
# Create a "frozen" distribution - i.e. a partially applied function
dist = stats.norm(10, 2)
#  same a rnorm
dist.rvs(10)
array([ 11.629 ,   9.5777,   8.5607,   8.5777,   8.6464,  11.5398,
        10.8751,  11.8244,  10.1772,   9.3056])
# same as pnorm
dist.pdf(np.linspace(5, 15, 10))
array([ 0.0088,  0.0301,  0.076 ,  0.141 ,  0.1919,  0.1919,  0.141 ,
        0.076 ,  0.0301,  0.0088])
# same as dnorm
dist.cdf(np.linspace(5, 15, 11))
array([ 0.0062,  0.0228,  0.0668,  0.1587,  0.3085,  0.5   ,  0.6915,
        0.8413,  0.9332,  0.9772,  0.9938])
# same as qnorm
dist.ppf(dist.cdf(np.linspace(5, 15, 11)))
array([  5.,   6.,   7.,   8.,   9.,  10.,  11.,  12.,  13.,  14.,  15.])

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文