Ohm
Ohm

Reputation: 2442

Inner loop for calculation and outer loop for saving results in Python

I would like to create a routine that saves results for ODE integration after certain amount of iterations. That it, the routine will receive variables for start time, finish time, step variable size and dt. dt is the variable for the time steps in the inner loop, and step is the time step for the outer loop - after each step time I would like to save the results, and to do so between start and finish. I used this routine, but something looks wrong - sometimes it shows that it saves the results after one step size, sometimes after step + dt:

import numpy as np

start = 0
finish = 10
step = 1
dt = 0.1
time_elapsed = start
for tout in np.arange(start+step,finish+step,step):
    while time_elapsed < tout:
        time_elapsed+=dt
        print "time step ", time_elapsed
    print "Outer_loop time ", time_elapsed

Can someone spot the bug? Also, any smart idea how can I do it using only for loops?

Upvotes: 1

Views: 133

Answers (1)

Netwave
Netwave

Reputation: 42678

You can just check the iteration over the step, check out the range for example below:

for i in xrange(start, finish):
    #do generic code
    if i % step: #check if the iteration is a step
         #do the step code you need

Upvotes: 1

Related Questions