Search code examples
pythonarraysloopsdata-storage

How to write every nth calculation to an array inside a for loop? (python)


I'm running a simulation in python that involves many many loops. Since my laptop has limited processing power, I want to write only every nth result to an array which stores my data. I looked online about slicing arrays, but could only find how to do it once a full-sized array had already been created. The for loop is below:

    def Simulate(time, steps):

            history_x = np.zeros(2000000)
            history_y = np.zeros(2000000)

            for i in range(2000000):
                    #calculate positions
                    a_x = ((-6.67e-11)*(mE)/((x**2 + y**2)))
                    a_y = ((-6.67e-11)*(mE)/((x**2 + y**2)))
                    v_x = v_x + (delta_t)*a_x
                    v_y = v_y + (delta_t)*a_y
                    y = y + (delta_t)*v_y + ((delta_t)**2)*a_y*0.5
                    x = x + (delta_t)*v_x + ((delta_t)**2)*(a_x)*0.5

                    rocket_history_x[i] = x
                    rocket_history_y[i] = y

(x,y, v_x, v_y and mE are all defined before the loop in my code, didn't want to clutter this post)

Essentially the maths isn't important, but I want history_x and history_y to only store every nth calculation of x and y. How do I do this?


Solution

  • Based on my comment above, a complete code would look like below. Here you initialize two empty lists instead of creating an array of length 2000000. Then you just save every nth value based on the if condition by enclosing the append statement within the if statements.

    def Simulate(time, steps):
        history_x, history_y = [[] for _ in range(2)] # initialize lists
        n = 10000
        for i in range(2000000):
            #calculate positions
            a_x = ((-6.67e-11)*(mE)/((x**2 + y**2)))
            a_y = ((-6.67e-11)*(mE)/((x**2 + y**2)))
            v_x = v_x + (delta_t)*a_x
            v_y = v_y + (delta_t)*a_y
            y = y + (delta_t)*v_y + ((delta_t)**2)*a_y*0.5
            x = x + (delta_t)*v_x + ((delta_t)**2)*(a_x)*0.5
            if i% n == 0: # Check for the step
                rocket_history_x.append(x) # store x here
                rocket_history_y.append(y) # store y here