我的Python代码计算时间太长了!我能用numpy更快地计算吗?如果是,怎么办?

2024-09-27 07:24:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我打算用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

Tags: newreturndefabscurrenthistorymasssun
2条回答

你好像陷入了一个无限循环。在

abs(x)给出一个数的绝对值,它总是正的。这意味着它永远不会低于-0.1,因此while循环永远不会结束。在

您需要将abs(x)或{}更改为其他内容。在

一个建议是定义“history”数组before your loop,而不是每次迭代都将其附加到它们。这样,就预先保留了一块内存。这将提高性能。但是,您需要提前计算出v_history和{}的大小。在

例如,使用1D阵列:

v_history = np.zeros((k,))
x_history = np.zeros((k,))

其中(k,)是数组的形状。在

然后需要使用索引值将计算的值存储在数组中

^{pr2}$

您可能还想开始考虑broadcasting

相关问题 更多 >

    热门问题