I am adapting Schorsch's answer in While loop inside for loop in Matlab to use in Python 3.5 for my problem.
I want to iterate over values in my t array. For each value, if the result of my calculation z converges (or doesn't converge after a maximum no. of iterations) I copy this to an array. Then I plot the results.
import numpy as np
import matplotlib.pyplot as plt
maxiter = 100 # max no. iterations in convergence loop
t = 0.05*np.arange(10)
z = 0.1 # initial guess
x = np.zeros(len(t)) # array for results
cvec = np.zeros(len(t)) # does loop converge?
for ii in t:
print(ii)
convergence = 0
while convergence == 0:
z_old = z
z = ii*np.random.rand() # perform calculations
# check convergence
if abs(z-z_old) < 0.01: # convergence
# store result
convergence = 1
x[ii] = z
cvec[ii] = convergence
elif abs(z-z_old) >= 0.01 and ii < maxiter: # no convergence but loop again
convergence = 0
else: # no convergence, move on to next value in t array
convergence = 0
x[ii] = 1e3
cvec[ii] = convergence
break
# plot result
plt.figure()
plt.plot(t[cvec==1],x[cvec==1],'x')
plt.xlabel('t')
plt.ylabel('x')
plt.show()
I get an error: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
lines = """
Does this mean I have to change how I index the while or for loops, and if so how should I do this?
x[ii], andiiis not an integer. Something is wrong with yourtarray (the one you use in the to iterate the for loop). If it is suppose to be integer array, but somehow is float, you can do something likefor ii in np.asarray(t, np.int32).xandcvecto an empty list before the loops then just append the values as needed i.e.x.append(z). Or, you could use a counter to indexxandcvecthen increment it everytime you set an element. If you need to store the time as well just set something liketimestamps = []and append to that as well.tarray with 1000 elements say, would it be more efficient to use theappendfunction or start with an array of zeros as in my MWE?for idx, ii in enumerate(t):and then just do the indexing withidxno need for a counter or to switch to lists :). Before I didn't realize you were storing the values forxin the case of non-convergence. See here forenumeratefunction.