I have come across something strange with numpy arrays in Python, and was wondering if anyone had an explanation. First let's start with something simple, which works as you'd expect:
CODE
>>> x = 6
>>> y = x
>>> y =3
>>> x
6
>>>
Now, the question: under what situations would the value of x become 3?
See the examples below to see what I mean. I've highlighted the lines that are changing with comments before and after.
CODE
from numpy import zeros, array, sqrt, loadtxt
rec_east = array(loadtxt("file.txt"), float)
# also load some other arrays:
# source_east, source_north, and rec_north
dist_x = zeros(rec_east.shape, float)
####


####
dist_y = dist_x
####


####
for j in range (0, 1):
for k in range(0, 1):
dist_x[j,k] = (rec_east[j,k] + source_east[j])/2
tval = (rec_east[j,k] + source_east[j])/2
####


####
#dist_y[j,k] = (rec_north[j,k] + source_north[j])/2
####


####
print tval, dist_x[j,k]
# output is:
# 323717.265 323717.265
This is what is expected: tval and dist_x are the same
Now, if the dist_y line is uncommented,
CODE
### ...
dist_x = zeros(rec_east.shape, float)
####


####
dist_y = dist_x
####


####
for j in range (0, 1):
for k in range(0, 1):
dist_x[j,k] = (rec_east[j,k] + source_east[j])/2
tval = (rec_east[j,k] + source_east[j])/2
####


####
dist_y[j,k] = (rec_north[j,k] + source_north[j])/2
####


####
print tval, dist_x[j,k]
# output is:
#323717.265 4464864.285
Not that the value of dist_x has changed. (Though not shown, it has changed to the value of dist_y[j,k].)
However, if the declaration of dist_y is changed, then the code works:
CODE
### ...
dist_x = zeros(rec_east.shape, float)
####


####
dist_y = zeros(rec_east.shape, float)
####


####
for j in range (0, 1):
for k in range(0, 1):
dist_x[j,k] = (rec_east[j,k] + source_east[j])/2
tval = (rec_east[j,k] + source_east[j])/2
####


####
dist_y[j,k] = (rec_north[j,k] + source_north[j])/2
####


####
print tval, dist_x[j,k]
# output is:
# 323717.265 323717.265
While I have figured out how to circumvent the problem, I don't really get why it was happening in the first place. Is there any reason why I should have expected this?
This post has been edited by ramz: 17 Jun, 2008 - 12:32 PM