我正在修改Schorsch在While loop inside for loop in Matlab中的答案,以便在Python3.5中针对我的问题使用。
我想迭代我的t数组中的值。对于每个值,如果我的计算结果是z收敛的(或者在最大值no之后不收敛)。)我将其复制到一个数组中。然后我画出结果。
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()我收到一个错误:VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future lines = """
这是否意味着我必须改变我对while或for循环的索引方式,如果是的话,我应该如何做呢?
发布于 2016-12-16 11:18:29
这个问题与行x[ii] =和cvec[ii]有关。当您试图访问非整数索引时。这些索引是在以下行生成的:
(...)
t = 0.05*np.arange(10) #[ 0. , 0.05, 0.1 , 0.15, 0.2 , 0.25, 0.3 , 0.35, 0.4 , 0.45]
(...)要解决这个问题,有几种方法可以这样做,但最简单的方法是访问t变量的值所在的相同索引。
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 idx, ii in enumerate(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[idx] = z
cvec[idx] = 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[idx] = 1e3
cvec[idx] = convergence
break
# plot result
plt.figure()
plt.plot(t[cvec==1],x[cvec==1],'x')
plt.xlabel('t')
plt.ylabel('x')
plt.show()使用while循环迭代值的最大次数,而不收敛
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 idx, ii in enumerate(t):
print(ii)
# Assume it wont converge
# So if we loop through all the max iterations and still no convergence, it is already marked
x[idx] = 1e3
cvec[idx] = 0
while iter in range(maxiter):
z_old = z
z = ii*np.random.rand() # perform calculations
if abs(z-z_old) < 0.01: # converge, therefore stop looping
x[idx] = z
cvec[idx] = 1
break
# plot result
plt.figure()
plt.plot(t[cvec==1],x[cvec==1],'x')
plt.xlabel('t')
plt.ylabel('x')
plt.show()https://stackoverflow.com/questions/41182709
复制相似问题