0

I am currently implementing a SOR(Successive Over Relaxation) and Gauss-Seidel method for a python project, the iterative process (all the calculations) in itself is working as expected when I call the function outside of main(), however, since the process is recursive and depends on two lists that change values every iteration, I believe the lists are not receiving their correct values accordingly, since python ends up printing the wrong answer. This is what I currently have for my main():

.
.
.
om=1
while om<2:
    k=0
    X=ite_SOR(X, Xp, om, i)[0]
    Xp=ite_SOR(X, Xp, om, i)[1]
    error=max(abs(abs(np.array(X)-abs(np.array(Xp)))))
    while error>1e-6:
        X=Xp[:]
        Xp=ite_SOR(X, Xp, om, i)[1]
        k+=1
    om+=0.2

The ite_SOR function is given as follows (I omitted the bulk of the function that I believe was not causing the problem since it is composed only of some weird calculations) :

def ite_SOR(X, Xp, om, n):
    for i in range(len(X)):
        
        ...

        Xp[i]=(1-om)*X[i]+om*(b + d + e + c)
    return X, Xp

This function takes both lists X and Xp and changes the list Xp in function of X. Returning the initial value of X and the new value of Xp (note that at the start of the process both lists are the same)

In the main() function both lists, X, and Xp end up being the same, which is not what I want. What needs to happen is X to receive the new value of Xp and run through ite_SOR(X, Xp, om, n) again and again until the error is smaller than 1e-6.

I have tried to print the values of X and Xp for every iteration, but both are always the same and never end up changing, up to a point where python only prints lists that contain nan, which I don't even know the meaning of.

Any help is greatly appreciated, if any more information is needed about my code, feel free to ask me.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Are `X` and `Xp` references to the same list? If so, modifying one of them modifies the other. You need to make a copy, it doesn't happen automatically when you assign. – Barmar Jun 10 '23 at 00:15

1 Answers1

0

It seems like X and Xp are being confused. In Python, it doesn't create a new object but rather creates a new reference to the existing object.

When you do X=Xp[:] in your while loop, you're creating a new list with same element as Xp

You can use copy()

om=1
while om<2:
    k=0
    X, Xp = ite_SOR(X.copy(), Xp.copy(), om, i)
    error=max(abs(abs(np.array(X)-abs(np.array(Xp)))))
    while error>1e-6:
        X=Xp.copy()
        _, Xp = ite_SOR(X.copy(), Xp.copy(), om, i)
        k+=1
    om+=0.2

copy() function is used to ensure that ite_SOR() is working with a new list, not a reference to the existing list.

Yuri R
  • 311
  • 2
  • 9