How to round whole matrix like numpy.round()

  1. how to round whole matrix like numpy.round()
  2. how to round SymPy Matrix in julia SymPy pakage
round.(your_matrix)
3 Likes

You can also explictly request rounding to a 64-bit integer.

julia> round.([3.4 5.6; 7.8 10.9])
2Ă—2 Matrix{Float64}:
 3.0   6.0
 8.0  11.0

julia> round.(Int, [3.4 5.6; 7.8 10.9])
2Ă—2 Matrix{Int64}:
 3   6
 8  11

The important character here is the . which “broadcasts” your function to each element of the matrix.

3 Likes
  1. how to round SymPy Matrix in julia SymPy pakage

Did you try round.(dh)?

yes. I tried. and the error is can’t round symbolic expression

Yes, what should that be? I mean, what would be expected? My guess is defining that to be a noop would be okay, right? Anyways, open an issue at SymPy.jl

Wait a minute, it’s not actually possible to numpy.round sympy expressions like yb, right? I never used sympy before, but I know numpy functions only work on some numerical types. Looking up your error and sympy rounding, it looks like it’s only possible after you give symbols values and convert the expressions to a numerical type with instance methods like yb.evalf or yb.round.

Assuming you can’t give any symbols values, you could skip those elements and round the rest:

julia> using SymPy
julia> @syms x, y
(x, y)
julia> m = [x            pi/2
            Sym("pi")/3  y   ]
2Ă—2 Matrix{Sym}:
    x  1.57079632679490
 pi/3                 y

julia> function roundtry(el, n)
         # I would prefer if-else, but neither sympy
         # nor Julia can simply test if .round works
         try
           el.round(n) # do not use Julia's round, it converts
         catch 
           el
         end
       end
roundtry (generic function with 1 method)

julia> roundtry.(m, 3)
2Ă—2 Matrix{Sym}:
    x  1.571
 pi/3      y

Note that Julia’s round does not work like the SymPy .round(n). I’m not sure if this is worth a PR, it is likely an intentional difference because Python-like dot-access syntax is a documented feature of SymPy.jl. It just means you shouldn’t use the same code for Matrix{Sym} as other Matrixes.

julia> round(m[3]; digits=3) |> typeof
Float64

julia> m[3].round(3) |> typeof
Sym

Yes, currently round in SymPy punts (with an error) on symbols and converts to a Julia number, then rounds non-symbols. SymPy’s round also doesn’t handle symbolic values. Perhaps, the following behaviour is more in line with the the OP wants: (x -> x.evalf(10)).(M). Either way, the round function in SymPy.jl could be improved.