数据分析师Python练习: 模拟弹道轨迹
以下是数据分析师Python的一个小练习,希望这个小练习可以对正在学习数据分析的同学有所帮助。也可以让在职的数据分析师有所启发。
数学建模要用导数知识:
感谢英国大神牛顿和德国大神莱布尼茨的导数求最值方法,当导弹的瞬时速度为0时,导弹高度达到最高值(峰值),看不懂的可以去补补微积分知识,高中课本就能看懂。
Python导入math模块,表示飞行时间t_flight:
t_flight = 2*u*math.sin(theta_radians)/g
这是代码运行的界面
运行后可以观察弹道数据,设置不同发射速度和角度可以得到不同结果。
生成的动态图:
生成动态图需要导入matplotlib模块。
说明此语句意思animation.FuncAnimation(fig,update,generate,interval=5)
animation.FuncAnimation函数用于生成动态图片。fig是生成的图表对象,generate函数生成数据后传递给update函数更新,这样数据不断更新,图形也不停变化。
interval表示时间间隔,设置的值越小,运动速度越快。
代码运行平台:
Canopy python 2.7,Windows32位系统
代码汇总
源代码添加详细注解,方便各位朋友阅读理解
# -*- coding: utf-8 -*-
'''
Animate the trajectory of an object inprojectile motion
'''
#seaborn增强背景效果
import seaborn
from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.font_manager importFontProperties
import math
g = 9.8
fig = plt.figure()
ax= fig.add_subplot(111)
ax.set_aspect('equal')
#中文字体路径 设置
font=FontProperties(fname=r"c:\windows\fonts\simsun.ttc",size=14)
#获取一个列表,有205个间隔数据,每个数据间隔0.005
def get_intervals(u, theta):
intervals = []
start = 0
interval = 0.005
while start < t_flight:
intervals.append(start)
start = start + interval
return intervals
#更新时间间隔参数,从而不断改变圆的圆心坐标位置,让其移动
def update(t):
x= u*math.cos(theta_radians)*t
y= u*math.sin(theta_radians)*t - 0.5*g*t*t
circle.center = x, y
return circle,
#产生时间间隔参数,(从0,0.005,0.01一直到1.02 )依次传递给updata函数
def generate():
for t in intervals:
yield t
def Print():
print u"初始速度(米/秒):",u
print u"发射角度(度)",theta
print u"飞行总时间(秒)",t_flight
print u"飞行距离(米)",xmax
#初始参数,u为初始速度,theta为发射角度
u = 30
theta =60
#返回一个角度的弧度值
theta_radians = math.radians(theta)
'''
Out[65]: 0.5235987755982988
'''
#导弹飞行总时间,运用导数知识可以求得公式
t_flight = 2*u*math.sin(theta_radians)/g
intervals = get_intervals(u, theta_radians)
'''
[0,
0.005,
0.01,
0.015,
0.02,
0.025,
0.10500000000000002,
0.11000000000000003,
0.11500000000000003,
.......
0.9900000000000008,
0.9950000000000008,
1.0000000000000007,
1.0050000000000006,
1.0100000000000005,
1.0150000000000003,
len(intervals)
Out[67]: 205
'''
xmin = 0
#x横轴最大距离
xmax =u*math.cos(theta_radians)*intervals[-1]
ymin = 0
t_max = u*math.sin(theta_radians)/g
#y横轴最大距离
#ymax = u*math.sin(theta)*t_max - 0.5*g*t_max**2
ymax =xmax
#设置坐标轴的x,y取值范围
ax = plt.axes(xlim=(xmin, xmax),ylim=(ymin, ymax))
#创建一个圆,圆点在(0,0),半径为0.2
circle = plt.Circle((xmin, ymin), 2)
ax.add_patch(circle)
#动画函数,让炮弹不断变化,generate产生数据传递给update更新
anim = animation.FuncAnimation(fig,update,generate,interval=5)
plt.title(u'导弹发射轨迹',fontproperties=font)
plt.xlabel(u'水平距离(米)',fontproperties=font)
plt.ylabel(u'导弹运行高度(米)',fontproperties=font)
plt.show()
#输出详细参数信息
Print()