convert symbolic matrix to numeric one

asked 2024-07-20 13:42:47 +0100

Karl007 gravatar image

updated 2024-07-20 14:03:54 +0100

vdelecroix gravatar image

Being new to sagemath I have the following problem: I have a rather large symbolic matrix M that depends on a collection of variables. the variables are collected in a list like this

sage: v = [var('val_%a' %i) for i in range(5) ]
sage: v
(val_0, val_1, val_2, val_3, val_4)

The Matrix M depends on some complicated way on the variables val_0 , val_1 etc... Now I want to evaluate M for some particular values val[i] which are numbers what I do is ceate a dictionary

sage: subsdict={ v[i]:i for i in range(5)}

and then substitute the values in M

sage: Mnumeric = M.subs(subsdict)

my problem is that this substitution is very slow (of course in the real problem its not only 5 variables but rather 100)

edit retag flag offensive close merge delete

Comments

Why not substitute before creating the matrix?

vdelecroix gravatar imagevdelecroix ( 2024-07-20 14:04:37 +0100 )edit

Complemlent to @vdelecroix's important remark :

... I have a rather large symbolic matrix M...

Isn't that the source of the problem ? Basically, what you want to do is necessarily equivalent to

matrix(SR, [[u.subs(subsdict) for u in v] for v in M])s

Therefore, you are doing M.nrows()*M.ncols() substitutions.

Ancilliary question : what is the desired type (or parent) of the elements of the substituted matrix ? According to your problem, it might be wise to convert the matrix elements

  • to QQ, AA, QQbar (if your elements are all rational, algebraix real or algebraic respectively), or

  • to RDF or CDF (if what you want to do with this matrix is essentially numeric).

Or possibly to the relevant Interval or Ball field (if you have to account for result precision).

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2024-07-20 16:22:52 +0100 )edit

Thanks for the quick answer. Yes, I guess I could construct the matrix as a numerical matrix instead of a symbolic first. I thought I could somehow do somthing similar as in Mathematica where the following works (and is fast)

In[1]:= M={{a,b},{c,d}}

In[3]:= a=1.5

In[4]:= M

Out[4]= {{1.5, b}, {c, d}}

In the end I would like to end up with a matrix of floats (I guess that's RDF in Sagemath?)

Karl007 gravatar imageKarl007 ( 2024-07-20 18:42:30 +0100 )edit

RDF would be machine floating point numbers. That should give you the fastest arithmetic. But you could also use

  • RealField: arbitrary precision floating point numbers (using mpfr in the background)
  • RealBallField: real balls (using arb in the background)
vdelecroix gravatar imagevdelecroix ( 2024-07-20 20:28:16 +0100 )edit