目录
一、实验九 利用类创建实现随机漫步和掷骰子
1.实验目的
理解和使用面向对象编程与使用,初步了解画图。(后面要讲matplotlib,先大家简单了解一下)
2.实验内容
仿编程序并修改,动行观看结果
3.实验步骤
自学相关知识(可自学学习通第10章内容),敲入参考代码运行,在理解代码原理基础上,根据不同测试内容改编程序。
4.随机漫步
(1)代码
#创建Random Walk类
from random import choice
class RandomWalk():
"""一个生成随机漫步数据的类"""
def __init__(self,num_points=5000):#初始化,两边各两个下划线,中间是init
"""初始化随机漫步的属性"""
self.num_points=num_points
#所有随机漫步都始于(0,0)
self.x_values=[0]
self.y_values=[0]
def fill_walk(self):#定义随机漫步方向
"""计算随机漫步包含的所有点"""
#不断漫步,直到列表达到所指定的长度
while len(self.x_values)<self.num_points:
#决定前进方向以及沿这个方向前进的距离
x_direction=choice([1,-1])
x_distance=choice([0,1,2,3,4])
x_step=x_direction * x_distance
y_direction=choice([1,-1])
y_distance=choice([0,1,2,3,4])
y_step=y_direction * y_distance
#拒绝原地踏步
if x_step==0 and y_step==0:
continue
#计算下一个点的x和y值
next_x=self.x_values[-1]+x_step
next_y=self.y_values[-1]+y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
#模拟多次随机漫步,并画图
import matplotlib.pyplot as plt
while True:
#创建一个Random Walk实例,并将其包含的点都绘制出来
rw=RandomWalk()
rw.fill_walk()
point_numbers=list(range(rw.num_points))
plt.scatter(rw.x_values,rw.y_values,c=point_numbers,
cmap=plt.cm.Blues,edgecolor='none',s=15)
#突出起点和终点
plt.scatter(0,0,c='green',edgecolors='none',s=100)
plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',
edgecolors='none',s=100)
plt.show()
keep_running=input("Make another walk?(y/n):")#人为控制随机漫步次数
if keep_running=='n':
break
2.结果
5.掷骰子
(1)代码
#创建掷骰子Die类
from random import randint
class Die():
"""表示一个骰子的类"""
def __init__(self,num_sides=6):
"""骰子默认为6面"""
self.num_sides=num_sides
def roll(self):
"""返回一个位于1和骰子面数之间的随机值"""
return randint(1,self.num_sides)
#掷骰子
#创建两个D6骰子
die_1=Die()
die_2=Die()
#掷骰子100次,并将结果存储到一个列表中
results=[]
for roll_num in range(100):
result=die_1.roll()+die_2.roll()
results.append(result)
print("掷个骰子100次,每次出现点数的结果为:\n",results)
print()
print("===========================================================")
#分析结果
frequencies=[]
max_result=die_1.num_sides+die_2.num_sides
for value in range(2,max_result+1):
frequency=results.count(value)
frequencies.append(frequency)
for i in range(2,max_result+1):
print("掷2个骰子100次,{0}点出现{1}次".format(i,frequencies[i-2]))
#结果可视化
import matplotlib.pyplot as plt
x=list(range(2,13))
y=[i/100 for i in frequencies]
plt.bar(x,y)
#设置x,y轴标签和字体
plt.xlabel('出现点数',fontproperties='simhei')
plt.ylabel('每点出现频率',fontproperties='simhei')
plt.title('掷2个骰子100次各点频率直方图',fontproperties='simhei',fontsize=14)
plt.show()
#出现点数累积分布函数图
z=[sum(y[:i]) for i in range(1,12)]
plt.bar(x,z)
plt.plot(x,z,color='red')
plt.plot([0,1]+x,[1 for i in range(0,13)],color='black',linewidth=1.5)
plt.xlabel('出现点数',fontproperties='simhei')
plt.ylabel('每点出现累积频率',fontproperties='simhei')
plt.title('出现点数累积分布函数图',fontproperties='simhei',fontsize=14)
plt.show()
(2)结果
二、实验十 利用numpy中的random画4个分布图
1.实验目的
1.熟练使用numpy中模块random的各种分布画分布图。(后面要讲matplotlib,先大家简单了解一下)
2.学会用扩展库tushare(老版本)及新版本获取金融数据。(根据提供的代码仿学)
2.实验内容
1.将第十周课堂讲的代码(见课件或视频)在IDLE 或 Jupyter Notebook中敲一遍。
2.编写程序,画分布图。
3.实验步骤
1.需敲入的代码见ppt课件或视频;(略)
2.自学相关知识,敲入参考代码运行,在理解代码原理基础上,根据不同测试内容改编程序。
3.学会用扩展库tushare(老版本)及新版本获取金融数据。(仿文件:进行,并自学)
4.分布图
(1)代码
import numpy.random as npr
import matplotlib.pyplot as plt
#当本程序在jupyter notebook运行时,需要加下条语句(在线画图)
#%matplotlib inline
size=1000
rn5=npr.binomial(100,0.2,size)#二项分布
rn6=npr.normal(10,20,size)#正态分布
rn7=npr.chisquare(0.5,size)#卡方分布
rn8=npr.poisson(2.0,size)#普松分布
fig,((ax1,ax2),(ax3,ax4))=plt.subplots(nrows=2,ncols=2,figsize=(10,10))
ax1.hist(rn5,bins=25)
ax1.set_title('binomial')
ax1.set_ylabel('frequency')
ax1.grid(True)
ax2.hist(rn6,bins=25)
ax2.set_title('normal')
ax2.grid(True)
ax3.hist(rn7,bins=25)
ax3.set_title('chisqare')
ax3.set_ylabel('frequency')
ax3.grid(True)
ax4.hist(rn8,bins=25)
ax4.set_title('poisson')
ax4.grid(True)
plt.show()
(2)结果
本文含有隐藏内容,请 开通VIP 后查看