我的For循环只通过一次。(我用的是Python)

问题描述 投票:-1回答:1

我使用Python,我有一个for循环,如下图所示。

def calculateTrajectories(masses, positions, velocities, T, dt):

    #create lists for where we want to know positions, velocities at some time and convert them to np arrays
    current_positions = []
    new_positions = np.array(current_positions)
    current_velocities = []
    new_velocities = np.array(current_velocities)

    #call updateParticles function to get new positions, velocities at each step
        #loop starts at 0, ends at T, has step value of dt
    for i in range(0, int(T), int(dt)):
        #show all the time steps in the total time range
        steps = np.array(i)

        #call updateParticles
        Positions, Velocities = updateParticles(masses, positions, velocities, dt)[i]

        #assign the position and velocity results to their respective lists to get turned into arrays
        current_positions.append(Positions)
        current_velocities.append(Velocities)

        return steps, current_positions, current_velocities

    return steps, new_positions, new_velocities

我试图用这个函数和for循环来做这个计算,它应该产生3个数组,分别是step、new_positions、new_velocities。

T4 = 8.64e7
dt4 = 8640
masses = [1.989e30, 5.972e24]
positions = [(-448794, 0.0, 0.0),(1.4959742e11, 0.0, 0.0)]
velocities = [(0.0, -8.94e02, 0.0),(0.0, 2.98e4, 0.0)]

calculation4 = calculateTrajectories(masses, positions, velocities, T4, dt4)
print(calculation4)

这就是我得到的结果。

(0, [array([ -448793.33565708, -7724160.        ,        0.        ])], [array([1.49597199e+11, 2.57472000e+08, 0.00000000e+00])])

updateParticles是另一个函数,但我已经检查过了,问题并不与此有关,肯定是与我在这里要做的函数calculateTrajectories有关。我不明白为什么我的循环只经过一次,而我给了它一个范围的值来经过。另外,在for循环的range()中,我不得不使用int()将停止值和步长值设为整数,因为如果我留下它们,就会出现类型错误,因为浮点数不能被解释为整数。

我怎样才能修正我的循环,使它能像range函数要求的那样多次通过呢? 谢谢你的帮助。

python function for-loop
1个回答
0
投票

由于你包含了一个 return 里面 for 循环,你定义的函数将在第一次通过时完成。

你可能会想把那个 return 彻底清除,并将 new_positionsnew_velocities 在你的循环下面。

© www.soinside.com 2019 - 2024. All rights reserved.