Issue
I'm using Sympy to do several symbolic computations in a Jupyter Notebook and I want to be able to get outputs of the form "x = [sympy expression] = [sympy expression]". If I just do something like
from sympy import symbols, diff
x = symbols('x')
y = diff(6*x**5)
y
It will display the value of y
using nice textbook style notation. The problem is if I try to combine text with Sympy expressions. If I simply put a Sympy expression in a print statement, it doesn't preserve the formatting but will display the result using standard Python syntax (I've tried using pprint
and all of Sympy's other print functions, but they didn't help). If I instead use the display
function from IPython, that renders the Sympy expressions correctly, but it will also put them on separate lines from the text. So, for instance, if I do
display(f"y ={y}")
the "y =" will be on a separate line from the expression for y. If I have several Sympy expressions in one display
statement, that results in things being needlessly broken up into several lines, which is a rather ugly output.
The only way I found around the unwanted line breaks is to wrap the Sympy expressions in IPython's Math
function, which seems to convert the Sympy expressions to regular Python syntax (e.g. x² becomes x**2), then use regular expressions to convert the Python syntax to LaTex syntax, which the Math
function will render properly (e.g. display(f'y = {re.sub('\*\*', '^', Math(y)}')
). It works, but it's a lot of hassle. Is there an easier way?
Solution
Actually I figured it out, so I'm posting my solution in case anyone else has a similar question: the need for directly using regular expressions to convert the sympy expression to LaTex the Math
can render can be avoided by using Sympy's LaTex function, which converts any sympy expression to LaTex syntax. So, doing, e.g.
from IPython.display import display, Math
from sympy import latex, symbols, diff
x = symbols('x')
y = diff(6*x**5)
display(Math(f' y = {latex(y)}'))
will give the single line output:
y = 30x⁴
which is exactly what I wanted (albeit, for more complicated expressions than the one I gave as an example).
Answered By - Mikayla Eckel Cifrese
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.