Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - write symbolic expression (sympy) to txt file

What is the best way to write a symbolic expression to a txt file (so that I can use the symbolic expression after reading the txt file)?

Is there a sympy equivalent of numpy's savetxt() function for example?

for example:

from sympy import Symbol
a=Symbol('a')
b=Symbol('b')

y=a+3*b

How can I properly write and read y?

like image 859
baklan Avatar asked Jul 08 '13 00:07

baklan


2 Answers

str(expr) in SymPy should save most of the information about your expression. The advantage is that it is human readable. The best way to load from it is to use sympify(), as opposed to just copy-paste or eval, because for example, str(Rational(1, 2)) will give 1/2, which will evaluate to 0.5 directly.

There is also a function srepr() (SymPy's version of repr) that gives a more verbose output.

One thing to be aware of is that neither saves information about assumptions on Symbols at the moment (Symbol('x', real=True)), so if you need that, you should use something like pickle or dill.

like image 147
asmeurer Avatar answered Sep 16 '22 20:09

asmeurer


You could use the pickle library to store it to a file (as you can save most Python objects):

import pickle
with open("y.txt", "w") as outf:
    pickle.dump(y, outf)

You would later load it with

with open("y.txt") as inf:
    y = pickle.load(inf)
like image 32
David Robinson Avatar answered Sep 20 '22 20:09

David Robinson