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?