评价收敛性

2024-09-28 21:57:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使我的计算收敛,但不起作用。我在for循环中迭代函数,当我得到容差时,我想打破循环。因此,函数给了我一个数组D[nr, nz],我在for循环中迭代他,每次我想比较上一次迭代和新的迭代,知道这个差值是否低于容差。但是在调用函数Ddif之前和之后,数组之间的差异是返回一个零向量。我认为我没有正确地传递值,也没有在相同的值之间进行区分,但我不知道为什么

nr = 8
nz = 10
def calculo(E):
    # my calcs
    #return an array D[nr,nz]
    return

ncolmns3 = (nr * nz)
cont_i = 0
Ddif = []

for a in range(0, 10000, 1):
    #before calling the function
    DOld2 = D
    #turning the array in an array of one row, and (nr * nz) columns
    DOld3 = numpy.reshape(DOld2, ncolmns3)

    D = calculo(D)

    #after calling the function
    DNew2 = D
    #turning the array in an array of one row, and (nr * nz) columns
    DNew3 = numpy.reshape(DNew2, ncolmns3)

    # Difference between before and after calling the function
    for i in range(0, ncolmns3, 1):
        Ddif.append(math.fabs(DOld3[i] - DNew3[i]))

    MaxDif = numpy.max(Ddif)
    #tolerance
    Tol = 0.01
    cont_i += 1
    if (MaxDif <= Tol) is True:
        break

print(cont_i)

Tags: andthe函数innumpyanforfunction
1条回答
网友
1楼 · 发布于 2024-09-28 21:57:51

当使用DOld2 = D时,您不会创建新数组,它是对D的引用。如果D发生变化,DOld2也会发生变化。(与DOld3相同)。你最终会计算: DOld2(=D)-DOld3(=D)=D-D=0

您应该运行的简化示例:

a=[1,2]
b=a
a[1]=7
print("CHANGE A")
print("a = ",a)
print("b = ",b)
b[0]=4
print("CHANGE B")
print("a = ",a)
print("b = ",b)

一个简单的解决方案:

DOld2 = numpy.array(D)
DNew2 = numpy.array(D)

PS:不要忘记在每次迭代开始时重置Ddif

相关问题 更多 >