I am trying to generate LaTeX
string expression for continued fractions in Jupyter Notebook
.
for example, a given Python list x=[1,2,3,4,5]
can be written as continued fraction:
Structure expression to generate this LaTeX
fraction is \\frac{Numerator}{Denominator}
With Non-recursive code :
from IPython.display import display, Markdown
# Non-recursive:
def nest_frac(previous_expr, numerator_expr1, denominator_expr2):
return previous_expr + " + \\frac{"+ numerator_expr1 + "}{" + denominator_expr2 + "}"
# Cumbersome, error-prone
display(Markdown("$"+ \
nest_frac("1","1", \
nest_frac("2","1", \
nest_frac("3","1", \
nest_frac("4","1", "5") \
) \
) \
) \
+ "$") \
)
x = [1,2,3,4,5]
How to recursively generate expression provided a python list.
We can define the function nest_frac_N
taking x
as an additional argument:
def nest_frac_N(previous_expr, numerator_expr1, denominator_expr2, x):
temp_frac=str(x[len(x)-1]-1) +"+ \\frac{"+str(numerator_expr1)+"}{"+str(x[len(x)-1])+"}"
for i in reversed(x[:len(x)-2]):
temp_frac = str(i) +"+ \\frac{1}{"+temp_frac+"}"
return temp_frac
If we need an output for x=[1,2,3,4,5]
we do:
>>> x = [1,2,3,4,5]
>>> nest_frac_N(1, 1, 1, x)
... '1+ \\frac{1}{2+ \\frac{1}{3+ \\frac{1}{4+ \\frac{1}{5}}}}'
To get the markdown format we use :
display(Markdown("$"+nest_frac_N(1, 1, 1, x)+"$"))
Let's the x
size to 10 to ensure that function is flexible :
Output
>>> x = [1,2,3,4,5,6,7,8,9,10]
>>> nest_frac_N(1, 1, 1, x)
... '1+ \\frac{1}{2+ \\frac{1}{3+ \\frac{1}{4+ \\frac{1}{5+ \\frac{1}{6+ \\frac{1}{7+ \\frac{1}{8+ \\frac{1}{9+ \\frac{1}{10}}}}}}}}}'
And to get the markdown :
display(Markdown("$"+nest_frac_N(1, 1, 1, x)+"$"))
And we can easily re-set the function in a way to display directly the markdown format.