0

As I am new to Python, I am having the following problem:

I have an initial numpy array which contains the initial values of my variables for a simulations. I want to update these according to some equations. Assuming that x_init is the array that has the initial values and it is a (5,3) array and x is the array that is used to update and store the values during each iteration, what i do is the following:

x = x_init
while x.min()<100:
  for j in range(3):
      for i in range(5):
        x[i,j]=x[i,j]+rand1

where rand1 is just a random number produced between [0,1]. In the end, the array x is always equal to x_init due to the assignment in the beggining (I assume). Can you please explain me why this happens and suggest a way to treat those kind of assignment in python?

Nisfa
  • 359
  • 1
  • 4
  • 16
  • Because `x` *is* whatever `x_init` referred to during the assignment. Assignment *never* implicitly copies. This is *always* how it works. – juanpa.arrivillaga Jun 01 '17 at 21:53
  • You should read and understand Ned Batchelder's [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html). Although `numpy` arrays are not mentioned, the principles still apply. – juanpa.arrivillaga Jun 01 '17 at 21:58
  • Also, keep in mind that the common idiom for copying sequences like lists using a slice in Python `my_list_copy = my_list[:]` does not actually create a copy of the underlying array with `numpy` arrays, and the slice is actually a *view*. – juanpa.arrivillaga Jun 01 '17 at 22:00
  • Thanks for the help! The guide you sent me is really helpful! – Nisfa Jun 02 '17 at 13:03

1 Answers1

0

You need to make a copy, since assigment will just give you a new way to refer to the same object.

For this specific case, use numpy.copy like this:

import numpy as np

b = np.ones((3,3))
a = np.copy(b)
a[1,1] += 1
print(b)
print(a)

https://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.html

fbence
  • 2,025
  • 2
  • 19
  • 42