遗忘海岸

江湖程序员 -Feiph(LM战士)

导航

匀加速运动模拟python,(matplotlib)

等距离方式

import numpy as np
import matplotlib
matplotlib.use("TKAgg")
import matplotlib.pyplot as plt

g=9.8
s=100
ds=0.00001 #单位米
v0=0.001 #m/s
v=[v0]
t=[ds/v0]
t_sum=0
ds_num=int(s/ds)
x=[]
y=[]
for i in range(ds_num+1):
    if i==0 :
        continue
    vi=v[i-1] + g * t[i-1]
    v.append(vi)
    ti=ds/vi
    t.append(ti)
    t_sum +=ti
    x.append(t_sum)
    y.append(ds * i)
    
fig,ax=plt.subplots()


x1=np.arange(0,np.sqrt(2*s/9.8),0.01)
y1=0.5 * g * x1**2

ax.plot(x,y, color='green',linewidth=0.1)
ax.plot(x1,y1, color='red', linewidth=0.1)
print(np.sqrt(20/9.8))
plt.show()
View Code

 等时间方式

import matplotlib
matplotlib.use("TKAgg")
import matplotlib.pyplot as plt
import numpy as np

# 初始参数
initial_velocity = 0  # 初始速度,单位是米/秒
acceleration = 9.8  # 加速度,单位是米/秒^2
time_step = 0.0001  # 时间步长,单位是秒
total_time = 1.428  # 总时间,单位是秒

# 计算总时间内的步数
num_steps = int(total_time / time_step)

# 存储每个时间步长的位移
displacements = []

# 存储每个时间步长的速度
velocities = []

# 模拟匀加速运动
for i in range(num_steps):
    # 计算当前时间步长的速度
    current_velocity = initial_velocity + acceleration * ( time_step)
    velocities.append(current_velocity)
    
    # 计算当前时间步长的位移
    current_displacement = ((initial_velocity + current_velocity) / 2) * time_step
    s=0
    if i>0:
        s=displacements[i-1]
        
    displacements.append(s + current_displacement)
    
    initial_velocity=current_velocity





# 绘制速度-时间图像
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot(np.arange(num_steps) * time_step, velocities, label='Velocity')
plt.xlabel('Time (s)')
plt.ylabel('Velocity (m/s)')
plt.title('Velocity-Time Graph')
plt.legend()

#绘制位移-时间图像
plt.subplot(1, 2, 2)
plt.plot(np.arange(num_steps) * time_step, displacements, label='Displacement')
plt.xlabel('Time (s)')
plt.ylabel('Displacement (m)')
plt.title('Displacement-Time Graph')
plt.legend()

# 显示图形
plt.tight_layout()
plt.show()
View Code

 

posted on 2024-02-11 21:40  遗忘海岸  阅读(14)  评论(0编辑  收藏  举报