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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With