matrix with fractional number

m = matrix(ZZ, 3, 3, lambda i, j: 1/(i + j) ); m

Sage tells me the following:

Traceback (click to the left of this block for traceback)

...

ZeroDivisionError: rational division by zero

why? it really confused me.

edit retag close merge delete

Sort by ยป oldest newest most voted

The problem is that matrix rows and columns are numbered from 0.

So the top left element of that matrix would be 1 / (0 + 0).

If you are thinking of rows and columns as numbered from 1, do this instead:

sage: m = matrix(QQ, 3, 3, lambda i, j: 1 / (i + j + 2)); m
[1/2 1/3 1/4]
[1/3 1/4 1/5]
[1/4 1/5 1/6]


or you can use another base ring such as RR or R in your example, if you defined R as a ring beforehand (in Sage, by default, R stand for the interpreter for the R statistics language).

more

Thank you very much. I see the problem and I change R to ZZ in my question.

( 2017-11-29 02:04:35 +0200 )edit

Alternatively, the matrix constructor can get an explicit list of lists (or the flat list associated to this one), instead of a function, and there is no confusion any longer. (Well, also using i will overwrite the default value of this variable in sage, which corresponds to $\sqrt{-1}$, i will use k and n instead of i, j .)

For instance:

sage: [ 1/(k+n) for k in [1..3] for n in [1..3] ]
[1/2, 1/3, 1/4, 1/3, 1/4, 1/5, 1/4, 1/5, 1/6]
sage: [ [ 1/(k+n) for k in [1..3] ] for n in [1..3] ]
[[1/2, 1/3, 1/4], [1/3, 1/4, 1/5], [1/4, 1/5, 1/6]]

sage: matrix( QQ, [ 1/(k+n) for k in [1..3] for n in [1..3] ] )    # bad
[1/2 1/3 1/4 1/3 1/4 1/5 1/4 1/5 1/6]

sage: matrix( QQ, 3, [ 1/(k+n) for k in [1..3] for n in [1..3] ] )
[1/2 1/3 1/4]
[1/3 1/4 1/5]
[1/4 1/5 1/6]
sage: matrix( QQ, 3, 3, [ 1/(k+n) for k in [1..3] for n in [1..3] ] )
[1/2 1/3 1/4]
[1/3 1/4 1/5]
[1/4 1/5 1/6]

sage: matrix( QQ, [ [ 1/(k+n) for k in [1..3] ] for n in [1..3] ] )
[1/2 1/3 1/4]
[1/3 1/4 1/5]
[1/4 1/5 1/6]
sage: matrix( QQ, 3, [ [ 1/(k+n) for k in [1..3] ] for n in [1..3] ] )
[1/2 1/3 1/4]
[1/3 1/4 1/5]
[1/4 1/5 1/6]
sage: matrix( QQ, 3, 3, [ [ 1/(k+n) for k in [1..3] ] for n in [1..3] ] )
[1/2 1/3 1/4]
[1/3 1/4 1/5]
[1/4 1/5 1/6]

more