Ask Your Question
1

Rounding entries of a matrix

asked 2023-01-11 18:54:37 +0100

Ello gravatar image

Given a matrix with real entries, how can I display that matrix with all entries rounded to a particular number of decimal places? The "round" function doesn't seem to work when you call a matrix instead of a scalar value.

edit retag flag offensive close merge delete

Comments

3 Answers

Sort by ยป oldest newest most voted
2

answered 2023-01-11 22:27:31 +0100

achrzesz gravatar image
m=matrix(RR,3,range(9));m

[0.000000000000000  1.00000000000000  2.00000000000000]
[ 3.00000000000000  4.00000000000000  5.00000000000000]
[ 6.00000000000000  7.00000000000000  8.00000000000000]

m.n(digits=4)

[0.0000  1.000  2.000]
[ 3.000  4.000  5.000]
[ 6.000  7.000  8.000]
edit flag offensive delete link more
1

answered 2023-01-12 13:06:13 +0100

Emmanuel Charpentier gravatar image

Alternative : the apply_map method :

sage: M=matrix([u/13 for u in range(9)], ncols=3) ; M
[   0 1/13 2/13]
[3/13 4/13 5/13]
[6/13 7/13 8/13]
sage: M.apply_map(lambda u:round(u,2))
[ 0.0 0.08 0.15]
[0.23 0.31 0.38]
[0.46 0.54 0.62]

HTH,

edit flag offensive delete link more
1

answered 2023-01-11 22:48:20 +0100

slelievre gravatar image

One way is to use less accurate floating point numbers.

This can be done using

  • the method change_ring of a matrix
  • the function RealField

Define a matrix:

sage: a = matrix(RR, 3, [j * 100./99 for j in (1 .. 9)])
sage: a
[1.01010101010101 2.02020202020202 3.03030303030303]
[4.04040404040404 5.05050505050505 6.06060606060606]
[7.07070707070707 8.08080808080808 9.09090909090909]

Change to 20-bit floating point numbers

sage: b = a.change_ring(RealField(20))
sage: b
[1.0101 2.0202 3.0303]
[4.0404 5.0505 6.0606]
[7.0707 8.0808 9.0909]
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

Stats

Asked: 2023-01-11 18:54:37 +0100

Seen: 757 times

Last updated: Jan 12 '23