每隔N步保存数组状态的技巧
时间:2025-09-03 09:30:37 123浏览 收藏
golang学习网今天将给大家带来《每隔 N 步保存数组状态的方法》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习文章或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!
本文旨在解决在模拟过程中,如何高效地保存数组状态,尤其是在需要控制内存使用,避免存储所有时间步数据的情况下。通过修改代码结构,实现在每隔 N 个时间步长后,将位置和速度数据写入文件或覆盖数组,从而优化存储空间,并提供相应的代码示例和调试建议。
在进行数值模拟时,经常需要保存模拟过程中的数据,例如位置、速度等。如果模拟时间很长,或者时间步长很小,那么存储所有时间步的数据将会占用大量的内存空间。为了解决这个问题,我们可以只保存每隔 N 个时间步长的数据,从而有效地减少内存的使用。
以下提供两种实现方式:
1. 使用数组覆盖
这种方法适用于不需要保留所有时间步数据的场景。通过在循环中覆盖数组的方式,只保留最新的 N 个时间步的数据。
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Constants M_Sun = 1.989e30 #Solar Mass G = 6.67430e-11 # m^3 kg^(-1) s^(-2) yr = 365 * 24 * 60 * 60 #1 year in seconds # Number of particles num_particles = 8 # Initial conditions for the particles (m and m/s) initial_pos = np.array([ [57.9e9, 0, 0], #Mercury [108.2e9, 0, 0], #Venus [149.6e9, 0, 0], #Earth [228e9, 0, 0], #Mars [778.5e9, 0, 0], #Jupiter [1432e9, 0, 0], #Saturn [2867e9, 0, 0], #Uranus [4515e9, 0, 0] #Neptune ]) initial_vel = np.array([ [0, 47400, 0], [0, 35000, 0], [0, 29800, 0], [0, 24100, 0], [0, 13100, 0], [0, 9700, 0], [0, 6800, 0], [0, 5400, 0] ]) # Steps t_end = 0.004 * yr #Total time of integration dt_constant = 0.1 intervals = 10000 #Number of outputs of pos and vel to be saved # Arrays to store pos and vel pos = np.zeros((num_particles, int(t_end), 3)) vel = np.zeros((num_particles, int(t_end), 3)) # Leapfrog Integration (2nd Order) pos[:, 0] = initial_pos vel[:, 0] = initial_vel saved_pos = [] saved_vel = [] t = 1 counter = 0 while t < int(t_end): r = np.linalg.norm(pos[:, t - 1], axis=1) acc = -G * M_Sun / r[:, np.newaxis]**3 * pos[:, t - 1] #np.newaxis for broadcasting with pos[:, i-1] # Calculate the time step for the current particle current_dt = dt_constant * np.sqrt(np.linalg.norm(pos[:, t - 1], axis=1)**3 / (G * M_Sun)) min_dt = np.min(current_dt) # Use the minimum time step for all particles half_vel = vel[:, t - 1] + 0.5 * acc * min_dt pos[:, t] = pos[:, t - 1] + half_vel * min_dt # Recalculate acceleration with the new position r = np.linalg.norm(pos[:, t], axis=1) acc = -G * M_Sun / r[:, np.newaxis]**3 * pos[:, t] #np.newaxis for broadcasting with pos[:, i-1] vel[:, t] = half_vel + 0.5 * acc * min_dt # Save the pos and vel here if counter % intervals == 0: saved_pos.append(pos[:,t].copy()) saved_vel.append(vel[:,t].copy()) t += 1 counter += 1 saved_pos = np.array(saved_pos) saved_vel = np.array(saved_vel) # Orbit Plot fig = plt.figure(figsize=(8, 8)) ax = fig.add_subplot(111, projection='3d') ax.scatter(0, 0, 0, color='yellow', marker='o', s=50, label='Sun') for particle in range(num_particles): x_particle = pos[particle, :, 0] y_particle = pos[particle, :, 1] z_particle = pos[particle, :, 2] ax.plot(x_particle, y_particle, z_particle, label=f'Particle {particle + 1} Orbit (km)') ax.set_xlabel('X (km)') ax.set_ylabel('Y (km)') ax.set_zlabel('Z (km)') ax.legend(loc='upper right', bbox_to_anchor=(1.1, 1.1)) ax.set_title('Orbits of Planets around Sun (km)') plt.show()
需要注意的是,原代码存在一个问题:
在保存 pos 和 vel 时,counter 的值比 t 小 1。这意味着当 counter % intervals == 0 时,pos[:, t] 还没有被更新,因此保存的是未更新的数据(初始值)。
解决方案:
- 将 pos[:,t].copy() 改为 pos[:, t-1].copy() 和 vel[:, t-1].copy():保存上一个时间步的数据,即已经计算过的数据。
- 将 t += 1 和 counter += 1 的位置互换:保证在保存数据时,t 和 counter 的值是一致的。
- 将判断条件修改为 if t % intervals == 0:由于 t 从 1 开始,因此需要使用 t % intervals == 0 来判断是否需要保存数据。
以下是修改后的代码:
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Constants M_Sun = 1.989e30 #Solar Mass G = 6.67430e-11 # m^3 kg^(-1) s^(-2) yr = 365 * 24 * 60 * 60 #1 year in seconds # Number of particles num_particles = 8 # Initial conditions for the particles (m and m/s) initial_pos = np.array([ [57.9e9, 0, 0], #Mercury [108.2e9, 0, 0], #Venus [149.6e9, 0, 0], #Earth [228e9, 0, 0], #Mars [778.5e9, 0, 0], #Jupiter [1432e9, 0, 0], #Saturn [2867e9, 0, 0], #Uranus [4515e9, 0, 0] #Neptune ]) initial_vel = np.array([ [0, 47400, 0], [0, 35000, 0], [0, 29800, 0], [0, 24100, 0], [0, 13100, 0], [0, 9700, 0], [0, 6800, 0], [0, 5400, 0] ]) # Steps t_end = 0.004 * yr #Total time of integration dt_constant = 0.1 intervals = 10000 #Number of outputs of pos and vel to be saved # Arrays to store pos and vel pos = np.zeros((num_particles, int(t_end), 3)) vel = np.zeros((num_particles, int(t_end), 3)) # Leapfrog Integration (2nd Order) pos[:, 0] = initial_pos vel[:, 0] = initial_vel saved_pos = [] saved_vel = [] t = 1 counter = 0 while t < int(t_end): r = np.linalg.norm(pos[:, t - 1], axis=1) acc = -G * M_Sun / r[:, np.newaxis]**3 * pos[:, t - 1] #np.newaxis for broadcasting with pos[:, i-1] # Calculate the time step for the current particle current_dt = dt_constant * np.sqrt(np.linalg.norm(pos[:, t - 1], axis=1)**3 / (G * M_Sun)) min_dt = np.min(current_dt) # Use the minimum time step for all particles half_vel = vel[:, t - 1] + 0.5 * acc * min_dt pos[:, t] = pos[:, t - 1] + half_vel * min_dt # Recalculate acceleration with the new position r = np.linalg.norm(pos[:, t], axis=1) acc = -G * M_Sun / r[:, np.newaxis]**3 * pos[:, t] #np.newaxis for broadcasting with pos[:, i-1] vel[:, t] = half_vel + 0.5 * acc * min_dt # Save the pos and vel here if t % intervals == 0: saved_pos.append(pos[:,t].copy()) saved_vel.append(vel[:,t].copy()) t += 1 counter += 1 saved_pos = np.array(saved_pos) saved_vel = np.array(saved_vel) # Orbit Plot fig = plt.figure(figsize=(8, 8)) ax = fig.add_subplot(111, projection='3d') ax.scatter(0, 0, 0, color='yellow', marker='o', s=50, label='Sun') for particle in range(num_particles): x_particle = pos[particle, :, 0] y_particle = pos[particle, :, 1] z_particle = pos[particle, :, 2] ax.plot(x_particle, y_particle, z_particle, label=f'Particle {particle + 1} Orbit (km)') ax.set_xlabel('X (km)') ax.set_ylabel('Y (km)') ax.set_zlabel('Z (km)') ax.legend(loc='upper right', bbox_to_anchor=(1.1, 1.1)) ax.set_title('Orbits of Planets around Sun (km)') plt.show()
2. 写入文件
这种方法适用于需要保留所有时间步数据,但又不想占用大量内存空间的场景。通过将数据写入文件,可以避免将所有数据都加载到内存中。
import numpy as np # 假设 pos 和 vel 是你的位置和速度数组 # N 是你想要保存数据的间隔 N = 10000 # 例如,每 10000 步保存一次 with open('positions.txt', 'w') as f_pos, open('velocities.txt', 'w') as f_vel: for t in range(int(t_end)): # 替换为你的时间步长循环 # 你的模拟代码... if t % N == 0: # 将当前位置和速度写入文件 np.savetxt(f_pos, pos[:,t].reshape(1,-1)) # 将数据reshape成二维数组,方便写入 np.savetxt(f_vel, vel[:,t].reshape(1,-1)) # 将数据reshape成二维数组,方便写入
注意事项:
- 使用调试器可以帮助你更好地理解代码的执行过程,并找到潜在的问题。
- 在选择保存数据的方式时,需要根据具体的应用场景进行权衡。如果需要保留所有时间步的数据,并且内存空间足够,那么可以使用数组存储。如果内存空间有限,或者只需要部分时间步的数据,那么可以使用文件存储。
- 在写入文件时,需要注意文件的格式和编码方式,以便后续读取和处理。
总结:
本文介绍了两种在模拟过程中保存数组状态的方法:使用数组覆盖和写入文件。通过选择合适的方法,可以有效地减少内存的使用,并提高模拟的效率。同时,也强调了调试的重要性,并提供了一些注意事项。希望这些内容能够帮助你更好地进行数值模拟。
今天带大家了解了的相关知识,希望对你有所帮助;关于文章的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
358 收藏
-
200 收藏
-
214 收藏
-
336 收藏
-
123 收藏
-
184 收藏
-
280 收藏
-
117 收藏
-
426 收藏
-
176 收藏
-
432 收藏
-
145 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 512次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 499次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习