Home > Blockchain >  Different function outputs for integers and numpy arrays
Different function outputs for integers and numpy arrays

Time:01-07

I am having trouble understanding, why I get different values in the following two cases:

-Case 1:

def myfunc(a,b,c):
    xx = a b
    yy = b c
    return xx, yy

q,w = myfunc(1,2,3)

print(q,w)

Output 1: 3 5

-Case 2:

import numpy as np

q=w=np.zeros(3)

def myfunc(a,b,c):
    xx = a b
    yy = b c
    return xx, yy


for i in range(3):
    q[i],w[i] = myfunc(1,2,3)

print(q,w)

Output 2: [5. 5. 5.] [5. 5. 5.]

In the second case, both arrays have their entries equal to 5. Could someone explain, why?

CodePudding user response:

I won't talk about the first case because it's simple and clear. For the second case, you have defined the variables q and w as following

q=w=np.zeros(3)

In this case, what ever changes you make in q they will be applied to w because they q and w have the same address.

When you run this:

q[i],w[i] = myfunc(1,2,3)

q[i] gets the value 3 and w[i] gets the value 5 and since q and w have the same address, q[i] will get the value 5 as well. That explains why you have 5 every time.

If you want to solve it, change the variable definition line from:

q=w=np.zeros(3)

to :

w=np.zeros(3)
q=np.zeros(3)
  •  Tags:  
  • Related