我一直在用python编写一个轨道物体的简单模拟。我终于让它工作了,但随着时间的推移,动画似乎在加速。我可以看到,我的轨道物体的速度是周期性的和正确的,但在动画中似乎移动得越来越快。我不知道为什么。在
import numpy as np
import math
from matplotlib import pyplot as plt
from matplotlib import animation
from time import sleep
import sys
fig = plt.figure()
"Defines useful information such as masses and initial velocities"
AU= (149.6e6 * 1000)
smass=1.98892*10**30 #kg mass of the sun
emass=5.9742*10**24 #kg mass of the earth
evx=0 #Earth velocity in the X direction
evy=29.783 * 1000 #Earth velocity in the Y direction
r=-1*AU #m #Earth Radius
G= 6.67408*10**-11 #m^3*kg^-1*s^-2
"Defines animated area and bodies"
ax = plt.axes(xlim=(-2*AU,2*AU), ylim=(-2*AU,2*AU))
earth = plt.Circle((0, 0), 6371000000, fc='b')
sun = plt.Circle((0,0), 6371000000, fc='y')
"Defines the starting positions of the bodies"
def init():
earth.center = (r,0)
sun.center = (0,0)
ax.add_patch(sun)
ax.add_patch(earth)
return earth,sun
"Calculates new positions of orbiting body (in this case Earth)"
def animate(i):
global evx
global evy
if i==0:
pass #this avoids a division by 0
else:
x, y = earth.center #Defines x and y
t=i*240 #Defines the time step
d=math.sqrt(x**2+y**2) #calculates distance between two objects
f=-(G*emass*smass)/(d**2) #calculates the force exerted on orbiting object
theta = math.atan2(y,x) #calculates the angle to the orbiting object
fx=math.cos(theta)*f #calculates the component of the force in the X direction on the orbiting object
fy=math.sin(theta)*f #calculates the component of the force in the Y direction on the orbiting object
evx+=fx/emass*t #calculates the velocity in the X direction of the orbiting object
evy+=fy/emass*t #calculates the velocity in the Y direction of the orbiting object
x += evx*t #converts velocity to X position using the time step
y += evy*t #converts velocity to Y position using the time step
earth.center = (x, y) #prints object at correct X and Y position
"Debug information"
#print ("distance is", d,"force is", f, "angle is", theta)
#print ("Speed is", math.sqrt(mvx**2+mvy**2))
#print ("x position is", x,"y position is",y,i)
"Watches for a collision between the two bodies distance is arbitrary"
if d<=6371000000:
print("Collision")
sys.exit()
else:
pass
return earth,sun
"Defines run time and animation information"
anim = animation.FuncAnimation(fig, animate,
init_func=init,
frames=360000,
interval=1,
blit=True)
plt.show()
目前没有回答
相关问题 更多 >
编程相关推荐