0

I'm trying to get the convergence of my calculations, but isn't working. I'm iterating the function through the for loop, and I want break the loop when I get the tolerance. So, the function gives me an array D[nr, nz], I iterate him in the for loop, and each time I want to compare the last iteration with the new iteration, to know if that difference is lower than the tolerance. But the difference between the arrays, before and after calling the function Ddif, is returning a vector of zeros. I think I am not passing the values correctly, and making the difference between the same values, but I don't know why.

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)
Marcelo
  • 77
  • 9
  • Likely every step there is in-place on `D` or pointers to `D`, and thus the reason `DOld3 - DNew3` is `0` is that `DOld3` and `DNew3` are pointing to the same data – Daniel F Nov 19 '20 at 14:15

1 Answers1

0

When using DOld2 = D you don't create a new array, it is a reference to D. If D changes, DOld2 does too. (same for DOld3). You end up calculating: DOld2(=D)-DOld3(=D) = D - D = 0

A simplified example you should run:

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)

A simple fix:

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

PS: Dont forget to reset Ddif at the beginning of each iteration

herisson
  • 128
  • 6
  • Thanks for the answer! as `DOld3` you mean `DNew2`? I tried what you said, but it didn't work. I also tried `DOld2 = D.copy()`, but also didn't work. – Marcelo Nov 19 '20 at 17:21
  • Yes, my mistake, answer is updated. You should print Ddif to check that it isn't equal to zero (using the fix above, it worked when i ran it), then you have to make sure that Ddif is reset at every loop iteration. (Ddif = []) – herisson Nov 21 '20 at 10:42