我使用Euler方法编写了以下代码,以绘制自由下落物体的速度与时间的关系图,最终达到最终速度:
import numpy as np
import matplotlib.pyplot as plt
g = -9.81
Cd = 0.47
p0 = 1.2
A = 0.0034
k = (Cd*p0*A)/2
m = 0.058
def euler(vyn, yn): #takes the starting velocity and height as arguments
i = 0
while i < 10000:
dt = 0.01
i += 1
vyn = vyn - dt * (g + ((k/m) * abs(vyn) * vyn))
yn = yn - dt * vyn
print(vyn, yn)
if yn < 0: #stops iterations when ball hits ground
break
return vyn
NumPoints = 2000
xmin = 0
xmax = 1000
dx = (xmax - xmin) / (NumPoints - 1)
xvals = [0.0] * NumPoints
yvals = np.zeros(NumPoints)
for i in range(NumPoints):
xvals[i] = xmin + i * dx
yvals[i] = euler(0,1000)
plt.plot(xvals,yvals)
plt.show()
顺便说一下,我把print语句放在while循环中,这样它就可以在每次迭代时从地面打印出物体的速度和高度,并且中断是这样的,当球击中时它会突破循环。地面。但是,当我在底部添加图形代码时,迭代会因某种原因循环回来,而不会中断。图表也不会打印出来。
删除print语句会产生图形,但它只是一条水平线。
如何修改代码以生成速度与时间的关系图,以及高度与时间的关系?我是否需要在while循环中嵌入图形代码?
由于