while和for循环中的Python索引问题

延髓

我正在Matlab中的while循环内的While循环中调整Schorsch的答案,以解决我的问题在Python 3.5中使用。

我想遍历t数组中的对于每个值,如果计算结果z收敛(或在最大迭代次数后不收敛),则将其复制到数组中。然后,我绘制结果。

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 = """

这是否意味着我必须更改对whilefor循环编制索引的方式,如果需要,该如何更改

阿德里亚诺·马丁斯(Adriano Martins)

问题与线条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()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章