Вызов и развитие функции внутри цикла for - PullRequest
0 голосов
/ 27 апреля 2020

Моя основная функция convertTrajectories определена ниже:

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

    #create lists for where we want to know positions, velocities at some time and convert them to numpy arrays
    current_positions = []
    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, T, dt):
        #show all the time steps in the total time range
        steps = np.array(i)

        #call updateParticles function
        Positions, Velocities = updateParticles(masses, positions, velocities, dt)

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

        #convert lists into numpy arrays
        new_positions = np.array(current_positions)
        new_velocities = np.array(current_velocities)

        #to make sure the calculation is working
        print(f"computing positions, velocities for time step {i}")

    return steps, new_positions, new_velocities

Функция updateParticles использует интеграторную схему, которая эволюционирует частицы в заданном временном диапазоне. Он принимает аргументы (массы, позиции, скорости, dt), где dt - значение шага по времени. Аргумент T в функции calcTrajectories - это общее время, за которое вычисление должно пройти от go до.

Я пытаюсь передать эти входные данные ниже в вышеуказанную функцию:

#from 1000 days into seconds
T4 = 86400000
#step value
dt4_test = 864000
#in kg
masses4 = [1.989e30, 5.972e24]
#converted to meters
positions4 = [(-448794, 0.0, 0.0),(1.4959742e11, 0.0, 0.0)]
#in m/s
velocities4 = [(0.0, -8.94e02, 0.0),(0.0, 2.98e4, 0.0)]

calculation4 = calculateTrajectories(masses4, positions4, velocities4, T4, dt4_test)
print(calculation4)

Я получаю правильный оператор печати со значением шага, а также я получаю массивы как для new_positions, так и для new_velocities. Однако массивы положения и скорости не меняются, они содержат одинаковые значения для каждого шага.

Как мне отредактировать мою функцию calcTrajectories, чтобы она выполняла вычисления с использованием самой предыдущей позиции и скорости, чтобы получить следующую, следующую и т. Д., Пока не истечет требуемое время? Или, другими словами, как я могу вызвать мою функцию updateParticles внутри для l oop, чтобы она всегда использовала new_positions и new_velocities с последнего шага l oop?

Спасибо за любую поддержку с это! * * 1013

1 Ответ

0 голосов
/ 27 апреля 2020

updateParticles непрерывно вызывается с исходными позициями и скоростями с помощью этой строки:

Positions, Velocities = updateParticles(masses, positions, velocities, dt)

Необходимо использовать последние позиции и скорости, как в:

Positions, Velocities = updateParticles(masses, current_positions[-1], current_velocities[-1], dt)

Новые вычисленияTrajectories функция

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

    #create lists for where we want to know positions, velocities at some time and convert them to numpy arrays
    current_positions = [positions]
    current_velocities = [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, T, dt):
        #show all the time steps in the total time range
        steps = np.array(i) #--this could be moved outside the for loop

        # call updateParticles function--pass in the latest position and velocities (i.e. last index of each array)
        Positions, Velocities = updateParticles(masses, current_positions[-1], current_velocities[-1], dt)

        # Update position and velocities
        current_positions.append(Positions)
        current_velocities.append(Velocities)

        #to make sure the calculation is working
        print(f"computing positions, velocities for time step {i}")

    #assign the position and velocity results to their respective lists to get turned into arrays
    # only need to convert to bumpy arrays once so moved outside for loop
    new_positions = np.array(current_positions)
    new_velocities = np.array(current_velocities)

    return steps, new_positions, new_velocities
...