Variable value is changing automatically

Asked

Viewed 70 times

0

I have a question about assigning values to variables. I created the following code for solving equation systems by the Gauss-Jacobi iterative method:

A = np.array([[2., -1.], [1., 2.]]) # Matriz de coeficientes
B = np.array([[1.], [3.]]) # Vetor de constantes
X = np.array([[0.], [0.]]) # Estimativa inicial
EA = 10**(-2) # Erro absoluto da solução do problema
erro = 1

while (erro > EA):
    Xp = tuple(X)
    print("\nO valor de Xp é:", Xp) # Aqui Xp está apresentando um valor
    for i in range(len(A)):
        s = 0
        for j in range(len(A)):
            if (i != j):
                s += A[i,j]*Xp[j]
        print("\nO valor de s é:", s)
        X[i] = (B[i] - s)/A[i,i]
    print("\nO valor de Xp é:", Xp) # Aqui Xp está apresentando outro valor, sendo que eu não alterei ele
    print("\nO valor de X é:", X)
    erro = np.amax(np.absolute(X - np.asarray(Xp)))

Initially, I set Xp to display the same value as X. Then I change only the value of X.

Whenever I run this code, the value of Xp is changing automatically, whenever I change the value of X. I tried to make Xp a tuple so that it doesn’t automatically change its value, but I didn’t succeed. What is the explanation for this and how to correct?

Throughout the code, I put comments indicating where my problem is occurring.

  • I believe you created a reference and not a copy. Use Xp = tuple(np.copy(X)), check the result and

  • Solved, thank you very much!

  • I’m glad you solved...

1 answer

1

Expensive,

Quickly, as you said in the comment:

"you created a reference and not a copy. Use Xp = tuple(np.copy(X))"

Explanation

As I put it in the comment, you created a reference to the existing variable instead of making a copy.

Several Python types have this feature. See below:

>>> a = [1]
>>> b = a
>>> b.append(2)
>>> b
[1, 2]
>>> a
[1, 2]
>>>

Note that the list a was changed by including an item in the list b. The latter (b) is only a reference to the list a.

To copy a list (and several other types of variables, there is the method copy. Vaja below:

>>> c = a.copy()
>>> c
[1, 2]
>>> c.append(3)
>>> c
[1, 2, 3]
>>> a
[1, 2]

This time, the list c received a copy of the list a and therefore by including an item in the list c did not cause any change in the list a.

See below that the same happens with set

>>> s = set(a)
>>> s
{1, 2}
>>> z = s
>>> z.add(3)
>>> z
{1, 2, 3}
>>> s
{1, 2, 3}
>>> w = s.copy()
>>> w.add(4)
>>> w
{1, 2, 3, 4}
>>> s
{1, 2, 3}

First a reference was created (z) and then a copy (w)

I will not lengthen this post, but I add that the same happens with dictionaries.

You can check through the function id

>>> a = [1,2]
>>> id(a)
4313065216
>>> b = a
>>> id(b)
4313065216

Realize it’s the same id

Understood the concept of reference and copy, we start to the why of this.

There are types mutable and immutable. By associating a variable of the changeable type to another variable, this creates a reference. On the other hand, by associating a variable of the immutable type to another variable, this creates a copy.

Type of Mutable Objects

  1. list
  2. Set
  3. Dictionary
  4. bytearray
  5. user defined classes

Type of Immutable Objects

  1. int
  2. float
  3. decimal
  4. Complex
  5. bool
  6. tuple
  7. crease
  8. bytes
  9. string

I hope I’ve helped

Browser other questions tagged

You are not signed in. Login or sign up in order to post.