Issue
Using Anaconda, I have written a simple code and I am at wit's end trying to figure out how an array keeps getting rewritten in a for loop after it's defined. I write the array (random 0 or 1s) named box and define a new array holder as a "copy" of the array I want to leave alone. However, box keeps getting rewritten and I just don't see how it should be doing this.
#FUNCTIONS
def initialize():
config = np.zeros([n, n])
for x in range(n):
for y in range(n):
if np.random.rand() < p:
config[x, y] = 1
return config
def roller(x):
test1 = np.roll(x,1,axis=0)
test2 = np.roll(x,1,axis=1)
test3 = np.roll(x,-1,axis=1)
test4 = np.roll(x,-1,axis=0)
hold = np.sum([test1,test2,test3,test4],axis=0)
return hold
def loop(steps,holder,store_config):
for t in range(steps):
tot = roller(holder)
for x in range(n):
for y in range(n):
if tot[x,y] >= 4:
holder[x,y] = 1
else:
holder[x,y] = 0
store_config[:,:,t] = holder
def func():
start = time.time()
time_steps = 20
store_config = np.zeros([n,n,time_steps])
loop(time_steps,holder,store_config)
end = time.time()
print(end - start, np.sum(store_config))
#CONSTANTS
n = 100
p = .2
box = initialize() #Array to leave ALONE
print(np.sum(box))
#Action
holder = box #Array to manipulate and redefine as box
func()
print(np.sum(box))
If you the value from the output of np.sum(box) should match before and after func() is ran , but they never do. The intention was that when I rerun func(), it spits out a value, but just iterates over the same defined "box" array but it keeps getting rewritten. I don't see how its possible. I thought arrays were treated like variables inside a function where they're not global? Each of the three sections #Functions, #Constants, and #Action would be in their own cells in a Conda Notebook.
Solution
I think the issue you are having is that arrays, just as lists and dicts, are assigned by reference. This happens no matter if it's a variable assignment or as an argument being passed to a function.
def f(x):
x[0] = 0
return x
a = array([1, 1])
b = f(a)
WILL result in a
and b
being equal, since x
is being manipulated and then returned. If you want to retain a
, you must copy the array first:
def f(x):
x_ = x.copy()
x_[0] = 0
return x_
I hope this clarifies things a bit. :-)
Answered By - dalum
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.