user3232357
user3232357

Reputation: 55

Python - linspace() shows strange behavior

I'm running into an issue with np.linspace(), and i have no idea why it behaves like this. My code looks like this:

x = linspace(0, 6, 3)
print 'x = ', x     # prints the correct values x =  [ 0.  3.  6.]
y = x; y *= 3; y += 3
print 'y = ', y     # prints the correct values y =  [  3.  12.  21.]
z = x; z *= 3; z -= 3
print 'z = ', z     # prints the correct values z =  [  6.  33.  60.]

# and then this ???
print x, y, z       # prints [  6.  33.  60.] [  6.  33.  60.] [  6.  33.  60.]

does somebody know why print x,y,z doesn't return the correct values as before (print x, print y, etc.? Do i have to convert x,y,z into separate, new arrays in order for them to print correctly? Thanks a ton in advance for the enlightenment!

Upvotes: 3

Views: 504

Answers (2)

Alejandro
Alejandro

Reputation: 3392

As ssm says, when you make y = x, y is pointing to the same place in the memory that x. So, any change in the y or x variable will affect both of them, just because both variables point to the same memory location! When you don't want this behaviour, it is recommended to use copy, as "ssm" suggest, or simply, you can multiply x by, let's say, 1: y = 1.0*x. The last has the same behaviour as x.copy(), but be aware of you can change the type of the variable.

Just as a curiosity: In case you deal with numpy arrays, the method copy is implemented, so, in order to make a copy of x, you can use

y = x.copy()

In general, if you want to copy any object in Python you can use deepcopy:

import copy
y = copy.deepcopy(x)

Upvotes: 1

ssm
ssm

Reputation: 5373

a numpy array points to the same memory location when you do assignment. For copying values to a new memory location do a y = x.copy()

Upvotes: 4

Related Questions