Python Solar System Simulation: A Visual Guide to Gravitational Interactions
from os import cpu_count\nimport numpy as np\nfrom numpy.random import rand\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\n%matplotlib qt5\nau,G,RE,ME = 1.48e11,6.67e-11,1.48e11,5.965e24\n\nm = np.array([3.32e5,0.055,0.815,1,0.107,317.8])MEG\nr = np.array([0,0.387,0.723,1,1.524,5.203])RE\nv = np.array([0,47.89,35.03,29.79,24.13,13.06])1000\n\ntheta = rand(len(m))np.pi2\ncTheta,sTheta = np.cos(theta), np.sin(theta)\nxyz = rnp.array([cTheta, sTheta, 0r]) #位置三分量,因为参数太多,所以把这三个分量写在了一起\nuvw = vnp.array([-sTheta, cTheta, 0v]) #速度三分量\n\nN_ast = 100\nm_ast = rand(N_ast)1e20\nr_ast = (rand(N_ast)3.5+1.6)RE\nv_ast = np.sqrt(G3.32e5ME/r_ast) #小行星速度sqrt(GM/R)\n\ntheta = rand(N_ast)np.pi2\nphi = (rand(N_ast)-0.5)0.3 #给一个随机的小倾角\ncTheta,sTheta = np.cos(theta), np.sin(theta)\ncPhi,sPhi = np.cos(phi),np.sin(phi)\n\nxyza = r_astnp.array([cThetacPhi, sThetacPhi, sPhi])\nuvwa = v_astnp.array([-sThetacPhi, cThetacPhi, sPhi])\nname = "solar.gif"\n\nfig = plt.figure(figsize=(10,10))\nax = fig.add_subplot(projection='3d')\nax.grid()\nax.set_xlim3d([-5.5RE,5.5RE])\nax.set_ylim3d([-5.5RE,5.5RE])\nax.set_zlim3d([-5.5RE,5.5RE])\n\ntraces = [ax.plot([],[],[],'-', lw=0.5)[0] for _ in range(len(m))]\npts = [ax.plot([],[],[],marker='o')[0] for _ in range(len(m))]\npt_asts = [ax.plot([],[],[],marker='.')[0] for _ in range(N_ast)]\n\nN = 500\ndt = 360050\nts = np.arange(0,Ndt,dt)\nxyzs,xyzas = [],[]\nfor _ in ts:\n xyz_ij = (xyz.reshape(3,1,len(m))-xyz.reshape(3,len(m),1))\n r_ij = np.sqrt(np.sum(xyz_ij2,0))\n xyza_ij = (xyz.reshape(3,1,len(m))-xyza.reshape(3,N_ast,1))\n ra_ij = np.sqrt(np.sum(xyza_ij2,0))\n \n for j in range(len(m)):\n for i in range(len(m)):\n if i!=j :\n uvw[:,i] += m[j]*xyz_ij[:,i,j]*dt/r_ij[i,j]**3\n for i in range(N_ast):\n uvwa[:,i] += m[j]xyza_ij[:,i,j]dt/ra_ij[i,j]**3\n \n xyz += uvwdt\n xyza += uvwadt\n xyzs.append(xyz.tolist())\n xyzas.append(xyza.tolist())\n\nxyzs = np.array(xyzs).transpose(2,1,0)\nxyzas = np.array(xyzas).transpose(2,1,0)\n\ndef animate(n):\n for i in range(len(m)):\n xyz = xyzs[i]\n traces[i].set_data(xyz[0,:n],xyz[1,:n])\n traces[i].set_3d_properties(xyz[2,:n])\n pts[i].set_data(xyz[0,n],xyz[1,n])\n pts[i].set_3d_properties(xyz[2,n])\n for i in range(N_ast):\n pt_asts[i].set_data(xyzas[i,0,n],xyzas[i,1,n])\n pt_asts[i].set_3d_properties(xyzas[i,2,n])\n return traces+pts+pt_asts\n\nani = animation.FuncAnimation(fig, animate, \n range(N), interval=10, blit=True)\n\nplt.show()\nani.save(name)\n你能用不同的方法完成上述代码的功能吗内容:是的,可以使用不同的方法来完成上述代码的功能。\n\n一种方法是使用类来组织代码。可以创建一个名为"SolarSystem"的类,其中包含初始化方法和动画方法。在初始化方法中,可以将所有变量和参数作为类属性进行初始化。然后,可以将动画方法定义为类方法,并使用类属性来计算和更新位置和速度。最后,可以创建一个类的实例,并调用动画方法来显示和保存动画。\n\n另一种方法是使用函数进行模块化。可以将代码分解为多个函数,每个函数负责执行特定的任务,例如计算位置和速度、更新位置和速度、绘制图形等。然后,可以创建一个主函数,通过调用这些函数来执行所有任务,并显示和保存动画。\n\n无论使用哪种方法,都需要确保在计算位置和速度时考虑到所有的相互作用,并在绘制图形时正确地更新对象的位置。
原文地址: https://www.cveoy.top/t/topic/pn91 著作权归作者所有。请勿转载和采集!