0

I have a number of mathematical objects created with SymPy, which display fine in Jupyter using "display". For example, there are a number of functions which I can display with:

display(f1(x))
display(f2(x))

and so on. But what I want is to prefix each line with some explanatory text, so the output is, for example:

Question 1: f1(x)

Question 2: f2(x)

with the functions f1(x), f2(x) displayed properly typeset (which "display" provides).

The nearest I've got is with matrices:

M = sympy.Matrix([["(a)",f1(x)],["(b)",f2(x)]])
display(M)

but this has two problems: (1) it shows the matrix delimiters, and (2) it strips the parentheses from "(a)" and "(b)".

So I'm still hoping for help: how to add a string to a line that uses "display". Thanks!

Alasdair
  • 1,300
  • 4
  • 16
  • 28
  • I really wish you had included some of your sympy examples, such as `f1(x)`, even if just toy examples. It would insure my suggestion matches what you are doing better than my guesses. – Wayne May 11 '23 at 16:50

1 Answers1

1

Option 1: Use Math()

I think the easiest would be to combine in the use of Math(), like here and sources therein.

import sympy as sym
from IPython.display import Math
x = sym.symbols('x')
I = sym.integrate(1/(1+x**2), (x, 0, 1))
y = 2
z = 4
Math(rf'\text{{Press 1 to compute }} {x}^{y} \text{{or 2 to compute }} \frac{y}{z} \text{{or something else all togeher different to computer}} {sym.latex(I)}')

Related to that is this post and this post.

That approach somewhat more translated to your example, that would be:

import sympy as sym
from IPython.display import Math
x = sym.symbols('x')
I = sym.integrate(1/(1+x**2), (x, 0, 1))
y = 2
z = 4
display(Math(rf'\text{{Question 1: }} {x}^{y}'))
display(Math(rf'\text{{Question 2: }} {sym.latex(I)}'))

Option 2: Use markdown with dollar signs to specify Latex

You can get very fancy with a variation on an example I built here that includes some sympy use combining markdown and f-strings:

from IPython.display import Markdown, display
def printmd(string):
    display(Markdown(string))
import sympy as sym
x = sym.symbols('x')
I = sym.integrate(1/(1+x**2), (x, 0, 1))
equation = r'$\int_{{t=0}}^1 \frac{{1}}{{1+t^2}}\,\text{d}t$'
printmd('**THE EQUATION:**')
printmd(f'Question 2: {equation}')
printmd('**THE RESULT:**')
printmd(f'Question 1 $  = {sym.latex(I)}$')
printmd('**OR, COMBINED:**')
printmd(f'Question 3: '+equation[:-2] + f' = {sym.latex(I)}$$')

I see that is a variation on this StackOverflow post.

Wayne
  • 6,607
  • 8
  • 36
  • 93
  • Thank you, Wayne, and indeed your method works well. As a toy example (have imported SymPy as sy): f = lambda x: x**2+3*x-4 Math(rf'\text{{Question 1: }} {sy.latex(f(x))}') – Alasdair May 12 '23 at 06:07