jupyter-notebooklatexnbconvert

What is the best way to write down in-line math equations in a jupyter notebook to have best LaTeX results?


When I am writing math equations in a markdown cell of a jupyter notebook, I casually put all of that in $ ... $. Today, I converted an .ipynb file to .tex, and realized most of these equations are converted into messy stuff in the output pdf. For instance, I realized it is converting all '$'s into '$'s.

This is an example of what has happened:

Jupyter Notebook markdown:

$ \nabla ^{2} f(x) = \frac{-1}{(x+1)^{2}} $

Tex Output:

\$ \nabla \^{}\{2\} f(x) = \frac{-1}{(x+1)^{2}} \$

Does anyone have any ideas why this is happening? Is there a better way to write down in-line math equations so that it is more compatible with LaTeX?


Solution

  • If you are eventually going to LaTeX version, the traditional advice is spelled out in minrk's comment from November 8 of 2012:

    "The best solution for that right now would be to use 'raw' cells instead of markdown, and just type LaTeX as you would. Then use nbconvert to turn the ipynb to TeX (code, figures and all), and run latex to render that to PDF, etc. You don't get live-rendered TeX in the browser like you do with MathJax / Markdown, but you do still have TeX / code in one document."

    The step where you are converting now is probably using nbconvert under the hood even if you aren't directly. (You may be using it directly since you tagged with 'nbconvert`.)

    Alternatively, if you are going to LaTeX ultimately, you may want to use a code cell and use the LaTeX magic cell line at the start of that cell. See here and here about %%latex cell magic. (You'll note it is also mentioned among the StackOverflow thread I referenced earlier.) In regards to the %%latex cell magic, I suggest actually consulting the link that leads use in an example notebook in this post because it seems it has to be full-blown LaTeX code and not just simple equations that work easily elsewhere with just dollar signs bracketing them, i.e., MathJax.

    I tried that option with your equation and when I output the notebook as LaTeX, I didn't see additional backslashes added. (I didn't however actually try rendering the LaTeX, and so I cannot address if all the cruft/boilerplate that Jupyter is adding causes any issues for downstream useability.)