给我一段模拟计算的python代码
- User
给我一段模拟计算的python代码
Assistant
以下是一段模拟计算的 Python 代码,它实现了一个简单的物理模拟:计算一个物体在重力作用下的自由落体运动。我们将使用基本的运动学公式来计算物体的位置和速度。
import numpy as np import matplotlib.pyplot as plt # 模拟参数 g = 9.81 # 重力加速度 (m/s^2) initial_velocity = 0 # 初始速度 (m/s) initial_height = 100 # 初始高度 (m) time_step = 0.01 # 时间步长 (s) total_time = 5 # 总模拟时间 (s) # 初始化变量 times = np.arange(0, total_time, time_step) # 时间数组 positions = [] # 存储每个时间点的高度 velocities = [] # 存储每个时间点的速度 # 当前状态 current_height = initial_height current_velocity = initial_velocity # 模拟循环 for t in times: # 更新速度和位置 current_velocity += g * time_step current_height -= current_velocity * time_step # 如果物体已经落地,则停止模拟 if current_height <= 0: current_height = 0 positions.append(current_height) velocities.append(current_velocity) break # 记录当前状态 positions.append(current_height) velocities.append(current_velocity) # 将时间数组裁剪到实际模拟的时间范围 times = times[:len(positions)] # 可视化结果 plt.figure(figsize=(10, 6)) plt.subplot(2, 1, 1) plt.plot(times, positions, label="Height (m)", color="blue") plt.title("Free Fall Simulation") plt.ylabel("Height (m)") plt.legend() plt.subplot(2, 1, 2) plt.plot(times, velocities, label="Velocity (m/s)", color="red") plt.xlabel("Time (s)") plt.ylabel("Velocity (m/s)") plt.legend() plt.tight_layout() plt.show()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.