我打算用Verlet算法计算行星运动。在
问题是,代码执行一个完整的周期大约需要30分钟。这是基本的计算,所以我不知道为什么要花这么长时间。在
我在这里读了一点,使用numpy
应该更快,对吧?在
但是我如何实现它呢?而且,它应该绕一整圈,停在0
(或者{
我的代码是:
grav = 6.673481*(10**-11) # = 6.673481e-11 # a direct way
m_sun = 1.989*(10**30) # = 1.989e+30
m_earth = 5.972*(10**24) # = 5.972e+24
r_earth = 149.59787*(10**9) # = 1.4959787e+11
def verlet_v( prev_v, prev_f, mass ):
current_v = ( prev_v + ( prev_f / mass ) )
print "New Velocity: %f" % current_v
return current_v
def verlet_x( prev_x, current_v ):
current_x = prev_x + current_v
print "New Position: %f" % current_x
return current_x
verlet_v( 20, 50, 3 )
v = 29.8*(10**3) # = 2.98e+04
x = 0
f = ( -grav * ( ( m_earth * m_sun ) / r_earth**2 ) )
v_history = []
x_history = []
while( abs(x) > ( -0.1 ) ): # ABS( <_anything_> ) is ALWAYS > -0.1
print "Mod(x): %f" % abs(x)
print "Limit: %f" % (0)
v = verlet_v( v, f, m_earth )
x = verlet_x( x, v )
v_history.append(v)
x_history.append(x)
print v_history
print x_history
你好像陷入了一个无限循环。在
abs(x)
给出一个数的绝对值,它总是正的。这意味着它永远不会低于-0.1
,因此while循环永远不会结束。在您需要将}更改为其他内容。在
abs(x)
或{一个建议是定义“history”数组before your loop,而不是每次迭代都将其附加到它们。这样,就预先保留了一块内存。这将提高性能。但是,您需要提前计算出}的大小。在
v_history
和{例如,使用1D阵列:
其中
(k,)
是数组的形状。在然后需要使用索引值将计算的值存储在数组中
^{pr2}$您可能还想开始考虑broadcasting
相关问题 更多 >
编程相关推荐