Strange behavior related to value / reference

Lambda stephenhsu9 at gmail.com
Tue Oct 27 22:15:36 EDT 2009


I defined a function to raise a 2x2 matrix to nth power:

def matrix_power(m, n):
  result = m[:]
  print result is m

  for i in range(n - 1):
    result[0][0] = result[0][0] * m[0][0] + result[0][1] * m[1][0]
    result[0][1] = result[0][0] * m[0][1] + result[0][1] * m[1][1]
    result[1][0] = result[1][0] * m[0][0] + result[1][1] * m[1][0]
    result[1][1] = result[1][0] * m[0][1] + result[1][1] * m[1][1]
    print result == m
    print "result:", result, "m:", m
  return result

And the output:
False
True
result: [[1, 2], [2, 5]] m: [[1, 2], [2, 5]]
True
result: [[5, 20], [20, 425]] m: [[5, 20], [20, 425]]
True
result: [[425, 17000], [17000, 289180625]] m: [[425, 17000], [17000,
289180625]]

I find the matrix and m lists are always equal.
But these two lists are separate objects, right?
What's wrong with this code?

BTW, numpy has such a function, but it doesn't support really large
number.
Does numpy has some functions that support arbitrarily large number?



More information about the Python-list mailing list