import numpy as np
from pylab import*
x=[]for i inrange(10000):
u = np.random.uniform(size=1)
v = np.random.uniform(size=1)
z = np.sqrt(-2*np.log(u))*np.cos(2*np.pi*v)#z = z * np.sqrt(2.0/512)
x.append(z)
y=[]
z=[]for i inrange(100):
y.append(0)
z.append(-4+i*0.08)for i inrange(10000):
tmp=(x[i]+4)/0.08if tmp >=0and tmp <100:
y[int(tmp)]+=1
plt.plot(z, y,'ro-', color='#4169E1', alpha=0.8, linewidth=1, label='example')
plt.legend(loc="upper right")
plt.xlabel('x')
plt.ylabel('y')
plt.show()
C++生成任意正态分布
#include<stdlib.h>#include<math.h>#define PI 3.14159265359floatNormalDistribution(float miu,float sigma){float u =1.0*rand()/RAND_MAX;float v =1.0*rand()/RAND_MAX;float z =sqrt(-2.0*log(u))*cos(2.0*PI*v);return miu + z * sigma;}intmain(){srand((unsigned)time(NULL));NormalDistribution(0,sqrt(2/512));}