XD blog

blog page

latex, programming, python, sphinx


2014-04-13 Latex formulas with Sphinx

Is it worth writing about something which took me 15 minutes to find out and others 15 to try? And it will be another 10 to write it down... I wonder! Anyway, I was looking for a way to add formulas in my python documentation.

First, it requires Latex (or Miktex on Windows). The basic installation is enough. Second, the file conf.py which configurates the documentation generation must contains the following lines:

extensions = [  # ... something
                'sphinx.ext.pngmath', 
                # ... something 
                ]
               
# the documentation of the two following binaries
# those paths works on Windows
pngmath_latex=r"C:\Program Files\MiKTeX 2.9\miktex\bin\x64\latex.exe"
pngmath_dvipng=r"C:\Program Files\MiKTeX 2.9\miktex\bin\x64\dvipng.exe"

After, it become simple to add a formula:

However, you should avoid writing too many formulas without compiling in between. The way sphinx reports about error is buggy (no message). The syntax to use is described Math support in Sphinx. Some examples:

.. math::

   (a + b)^2  &=  (a + b)(a + b) \\
              &=  a^2 + 2ab + b^2
              
.. math::
   :nowrap:

   \begin{eqnarray}
      y    & = & ax^2 + bx + c \\
      f(x) & = & x^2 + 2xy + y^2
   \end{eqnarray}
   
.. math:: e^{i\pi} + 1 = 0
   :label: euler

Euler's identity, equation :eq:`euler`, was elected one of the most
beautiful mathematical formulas.   

Inline:

Since Pythagoras, we know that :math:`a^2 + b^2 = c^2`.

<-- -->

Xavier Dupré