Ask Your Question
1

matrix with fractional number

asked 2017-11-28 15:32:59 +0100

lijianing gravatar image

updated 2017-11-29 02:04:46 +0100

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 flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
2

answered 2017-11-28 18:04:23 +0100

slelievre gravatar image

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).

edit flag offensive delete link more

Comments

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

lijianing gravatar imagelijianing ( 2017-11-29 02:04:35 +0100 )edit
1

answered 2017-11-29 09:39:50 +0100

dan_fulea gravatar image

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]
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2017-11-28 15:32:59 +0100

Seen: 658 times

Last updated: Nov 29 '17