from
numpy
import
random
randarray
=
random.random(size=(2,4))
random函数接收需要生成随机矩阵的形状的元组作为唯一参数。上面的代码将会返回一个两行四列的随机矩阵,随机数的值位于0到1之间,矩阵是numpy.array类型。除了random函数外,还有生成整数随机矩阵的函数randint等等。
import random #导入随机数模块m=10
n=10
matrix = [[0 for i in range(m)] for i in range(n)] #定义数组
for row in range(0,m):
for col in range(0,n):
matrix[row].append(random.randint(0,101)) #赋值
for row in range(0,m):
print matrix[row]#打印
结果
一般的正态分布可以通过标准正态分布配合数学期望向量和协方差矩阵得到。如下代码,可以得到满足一维和二维正态分布的样本。希望有用,如有错误,欢迎指正!# coding=utf-8
import numpy as np
from numpy.linalg import cholesky
import matplotlib.pyplot as plt
sampleNo = 1000
# 一维正态分布
# 下面三种方式是等效的
mu = 3
sigma = 0.1
np.random.seed(0)
s = np.random.normal(mu, sigma, sampleNo )
plt.subplot(141)
plt.hist(s, 30, normed=True)
np.random.seed(0)
s = sigma * np.random.randn(sampleNo ) + mu
plt.subplot(142)
plt.hist(s, 30, normed=True)
np.random.seed(0)
s = sigma * np.random.standard_normal(sampleNo ) + mu
plt.subplot(143)
plt.hist(s, 30, normed=True)
# 二维正态分布
mu = np.array([[1, 5]])
Sigma = np.array([[1, 0.5], [1.5, 3]])
R = cholesky(Sigma)
s = np.dot(np.random.randn(sampleNo, 2), R) + mu
plt.subplot(144)
# 注意绘制的是散点图,而不是直方图
plt.plot(s[:,0],s[:,1],'+')
plt.show()