lundi 26 octobre 2020

If/break test for convergence triggering too early in python

I'm trying to use an if statement to check when the approximated values converge, but it keeps returning that it converges after 2 iterations, which it shouldn't since removing the if-break statement and setting it to 1000 iterations gets very different values.

def Jacobi2D(U,xrange,yrange,order):
    Up=sym.zeros(len(xrange),len(yrange))
    for k in range(1,order):
        if k>=2 and U==Up:
            print('Approximation converges after',k,'iterations')
            break
        Up=U #Save the U of the previous iteration for use in the formula
        for i in range(1,len(xrange)-1):
            for j in range(1,len(yrange)-1):
                U[i,j]=Up[i,j]+(1/4)*(Up[i+1,j]+Up[i-1,j]+Up[i,j+1]+Up[i,j-1]-4*Up[i,j])
                continue
            continue
        continue
    return U

The function takes U as a matrix with dimensions (len(xrange),len(yrange)) and 'order' is how many iterations you want the approximation to go through. Does anyone know why the condition is being triggered before redefining Up=U? Any help would be appreciated, thank you!

Aucun commentaire:

Enregistrer un commentaire