1

A Hilbert matrix is a square matrix whose elements are given by:

 A[i][j]= 1 / (i+j+1)

My code is:

def Hilbert(n):
    H = [[0]*n]*n
    for i in range(n):
        for j in range(n):
            H[i][j] = 1/(i+j+1)
    return H

e.g. for n = 3 it should return

[1, 1/2, 1/3]  
[1/2, 1/3, 1/4]  
[1/3, 1/4, 1/5]

but it returns 3 rows of

[1/3, 1/4, 1/5]  

where's my mistake?

2 Answers2

0

When you do

H = [[0]*n]*n

the last *n makes shallow copies of the first [0 0 0 .... (n)] list. By modifying any of the elements in the first column, you change all the columns (the items inside the lists are references to the first).

Numpy is good for array manipulation, but if you don't want to use it try

H = [[0]*n for i in xrange(n)]

To see if you have elements that point to the same integer, you can try

for i in range(n):
    for j in range(n):
        print(id(H[i][j])) # [id() is the memory address](https://docs.python.org/2/library/functions.html#id)

Aside: Using numpy it's

H = np.zeros((n, n))

ref : https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.zeros.html

ehacinom
  • 8,070
  • 7
  • 43
  • 65
0

The mistake is in the H init part:

H = [[0]*n]*n

This create list of references to the same, inner, list. Thus all rows return the same value.

Try with:

H = [[0]*n for i in range(n)]

emirc
  • 1,948
  • 1
  • 23
  • 38