How can I display LaTeX code in a IPython Notebook?
IPython notebook uses MathJax to render LaTeX inside html/markdown. Just put your LaTeX math inside $$.
$$c = \sqrt{a^2 + b^2}$$
Or you can display LaTeX / Math output from Python, as seen towards the end of the notebook tour:
from IPython.display import display, Math, Latex
display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))
This came up in a search I was just doing, found a better solution with some more searching, IPython notebooks now have a %%latex magic that makes the whole cell Latex without the $$ wrapper for each line.
Refer notebook tour for Rich Display System
LaTeX References:
Udacity's Blog has the Best LaTeX Primer I've seen: It clearly shows how to use LaTeX commands in easy to read, and easy to remember manner !! Highly recommended.
This Link has Excellent Examples showing both the code, and the rendered result !
You can use this site to quickly learn how to write LaTeX by example.
And, here is a quick Reference for LaTeX commands/symbols.
To Summarize: various ways to indicate LaTeX in Jupyter/IPython:
Examples for Markdown Cells:
inline, wrap in: $
The equation used depends on whether the the value of
$Vmax$ is R, G, or B.
block, wrap in: $$
$$H← 0 + \frac{30(G−B)}{Vmax−Vmin} , if Vmax = R$$
block, wrap in: \begin{equation} and \end{equation}
\begin{equation}
H← 60 + \frac{30(B−R)}{Vmax−Vmin} , if Vmax = G
\end{equation}
block, wrap in: \begin{align} and \end{align}
\begin{align}
H←120 + \frac{30(R−G)}{Vmax−Vmin} , if Vmax = B
\end{align}
Examples for Code Cells:
LaTex Cell: %%latex magic command turns the entire cell into a LaTeX Cell
%%latex
\begin{align}
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}
Math object to pass in a raw LaTeX string:
from IPython.display import Math
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
Latex class. Note: you have to include the delimiters yourself. This allows you to use other LaTeX modes such as eqnarray:
from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}""")
Docs for Raw Cells:
(sorry, no example here, just the docs)
Raw cells
Raw cells provide a place in which you can write output directly. Raw cells are not evaluated by the notebook. When passed through nbconvert, raw cells arrive in the destination format unmodified. For example, this allows you to type full LaTeX into a raw cell, which will only be rendered by LaTeX after conversion by nbconvert.
Additional Documentation:
For Markdown Cells, as quoted from Jupyter Notebook docs:
Within Markdown cells, you can also include mathematics in a straightforward way, using standard LaTeX notation: $...$ for inline mathematics and $$...$$ for displayed mathematics. When the Markdown cell is executed, the LaTeX portions are automatically rendered in the HTML output as equations with high quality typography. This is made possible by MathJax, which supports a large subset of LaTeX functionality
Standard mathematics environments defined by LaTeX and AMS-LaTeX (the amsmath package) also work, such as \begin{equation}...\end{equation}, and \begin{align}...\end{align}. New LaTeX macros may be defined using standard methods, such as \newcommand, by placing them anywhere between math delimiters in a Markdown cell. These definitions are then available throughout the rest of the IPython session.
Use $$ if you want your math to appear in a single line, e.g.,
$$a = b + c$$ (line break after the equation)
If you don't need a line break after the math, use single dollar sign $, e.g.,
$a = b + c$ (no line break after the equation)
You can choose a cell to be markdown, then write latex code which gets interpreted by mathjax, as one of the responders say above.
Alternatively, Latex section of the iPython notebook tutorial explains this well.
You can either do:
from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}""")
or do this:
%%latex
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}
More info found in this link
I developed prettyPy, which offers a nice way to print equation. Unfortunately, it's not performant and needs testing.
Example:
Granted, sympy is a great alternative and although prettyPy doesn't allow for evaluating expressions, variable initialization is not required.
I wrote how to write LaTeX in Jupyter Notebook in this article.
You need to enclose them in dollar($) signs.
To align to the left use a single dollar($) sign.
$P(A)=\frac{n(A)}{n(U)}$
To align to the center use double dollar($$) signs.
$$P(A)=\frac{n(A)}{n(U)}$$
Use \limits for \lim, \sum and \int to add limits to the top and the bottom of each sign.
Use a backslash to escape LaTeX special words such as Math symbols, Latin words, text, etc.
Try this one.
$$\overline{x}=\frac{\sum \limits _{i=1} ^k f_i x_i}{n} \text{, where } n=\sum \limits _{i=1} ^k f_i $$
Matrices
Piecewise functions
$$
\begin{align}
\text{Probability density function:}\\
\begin{cases}
\frac{1}{b-a}&\text{for $x\in[a,b]$}\\
0&\text{otherwise}\\
\end{cases}
\\
\text{Cumulative distribution function:}\\
\begin{cases}
0&\text{for $x<a$}\\
\frac{x-a}{b-a}&\text{for $x\in[a,b)$}\\
1&\text{for $x\ge b$}\\
\end{cases}
\end{align}
$$
The above code will create this.
If you want to know how to add numbering to equations and align equations, please read this article for details.
Since, I was not able to use all the latex commands in Code even after using the %%latex keyword or the $..$ limiter, I installed the nbextensions through which I could use the latex commands in Markdown. After following the instructions here: https://github.com/ipython-contrib/IPython-notebook-extensions/blob/master/README.md and then restarting the Jupyter and then localhost:8888/nbextensions and then activating "Latex Environment for Jupyter", I could run many Latex commands. Examples are here: https://rawgit.com/jfbercher/latex_envs/master/doc/latex_env_doc.html
\section{First section}
\textbf{Hello}
$
\begin{equation}
c = \sqrt{a^2 + b^2}
\end{equation}
$
\begin{itemize}
\item First item
\item Second item
\end{itemize}
\textbf{World}
As you see, I am still unable to use usepackage. But maybe it will be improved in the future.
The answer given by minrk (included for completeness) is good, but there is another way that I like even more.
You can also render an entire cell as LaTeX by typing %%latex as the first line in a text cell. This is usefull if you
want more control,
want more than just a math environment,
or if you are going to write a lot of math in one cell.
minrk's answer:
IPython notebook uses MathJax to render
LaTeX inside html/markdown. Just put your LaTeX math inside $$.
$$c = \sqrt{a^2 + b^2}$$
Or you can display LaTeX / Math output from Python, as seen towards
the end of the notebook
tour:
from IPython.display import display, Math, Latex
display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))
If your main objective is doing math, SymPy provides an excellent approach to functional latex expressions that look great.
Using LaTeX syntax directly in a Markdown cell works for me. I'm using Jypiter 4.4.0.
I don't have to use %%latex magic command, I insist, simply a markdown cell:
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}
Renders to:
I came across this problem some day using colab. And I find the most painless way is just running this code before printing. Everything works like charm then.
from IPython.display import Math, HTML
def load_mathjax_in_cell_output():
display(HTML("<script src='https://www.gstatic.com/external_hosted/"
"mathjax/latest/MathJax.js?config=default'></script>"))
get_ipython().events.register('pre_run_cell', load_mathjax_in_cell_output)
import sympy as sp
sp.init_printing()
The result looks like this:
I am using Jupyter Notebooks.
I had to write
%%latex
$sin(x)/x$
to get a LaTex font.
Yet another solution for when you want to have control over the document preamble. Write a whole document, send it to system latex, convert the pdf to png, use IPython.display to load and display.
import tempfile
import os.path
import subprocess
from IPython.display import Image, display
with tempfile.TemporaryDirectory(prefix="texinpy_") as tmpdir:
path = os.path.join(tmpdir, "document.tex")
with open(path, 'w') as fp:
fp.write(r"""
\documentclass[12pt]{standalone}
\begin{document}
\LaTeX{}
\end{document}
""")
subprocess.run(["lualatex", path], cwd=tmpdir)
subprocess.run(["pdftocairo", "-singlefile", "-transp", "-r", "100", "-png", "document.pdf", "document"], cwd=tmpdir)
im = Image(filename=os.path.join(tmpdir, "document.png"))
display(im)
If you want to display a LaTeX equation from a notebook code cell you can create a simple wrapper class that makes use of the Jupyter notebooks rich display representation. This class should have a _repr_latex_ method (note this single underscore at the start and end rather than the double underscores of other special methods) that outputs the LaTeX string. E.g.:
class LaTeXEquation:
def __init__(self, eqntext):
self.eqntext = eqntext
def __repr__(self):
return repr(self.eqntext)
def _repr_latex_(self):
"""
Special method for rich display of LaTeX formula.
"""
# add $'s at start and end if not present
if self.eqntext.strip()[0] != "$" and self.eqntext.strip()[-1] != "$":
return "$" + self.eqntext + "$"
else:
return self.eqntext
myeqn = "x = y^2"
Then in a code cell, if you do, e.g.,
LaTeXEquation(myeqn)
it will show the formatted equation.
Related
I've been trying to find a solution to align multiple equations in Marp (a tool to convert .md files into PDF) but can't find a solution.
I tried using \begin{equation}......\end{equation}(which apparently is not supported in Marp), and various combinations of $....$, $$....$$
but can't find a hack.
I'm trying to generate something like :
but instead I get this:
here is my code:
$$ E_{\theta}[\theta] = \int_{\theta}\theta\ p(\theta)\ d\theta $$
$$ E_D[E_{\theta}[\theta|D]] = \int_D\Bigg\{\int_{\theta}\theta\ p(\theta|D)\ d\theta \Bigg\}\ p(D)\ dD $$
What am I missing. There is a solution for R Markdown, but I'm not sure if Marp supports R Markdown. I also can't find a way to import packages in Marp too.
Please help. Thanks.
Put $$ at the start and end of the equations - but not after each each equation.
Then separate each equation with \\.
Put an & before each equals (where you want it to align)
Use the \begin{aligned} and \end{aligned} function.
Here is a simple example:
$$\begin{aligned} 1 + 2 + 3 + 4 &= 10 \\
20 \times 80 &= 1600 \end{aligned}$$
Here is your example in this format:
$$\begin{aligned}E_{\theta}[\theta] &= \int_{\theta}\theta\ p(\theta)\ d\theta \\
E_D[E_{\theta}[\theta|D]] &= \int_D\Bigg\{\int_{\theta}\theta\ p(\theta|D)\ d\theta \Bigg\}\ p(D)\ dD \end{aligned}$$
These these examples when rendered:
math-alignement-results
According to this Rich Display System example the Jupyter notebook can display latex using the %%latex cell magic.
The example given using the align environment works fine on my system (Notebook Server 3.2.0-8b0eef4) but when I try and show a tabular or a table, the result is just nicely typesetting Latex code!
Is there some kind of preamble I need to add to make this work?
Answer
Jupyter builds on MathJax and cite "MathJax doesn't implement tabular". The link also shows the recommended array environment as tabular replacement.
Workaround:
Latex can also be used in Markdown cells (Celltype Markdown instead of Code). You can select the left area besides the cell and press "m" key or via Cell>Cell-Type in top menu. Then you could use html for the table.
<table>
<tr>
<td>
\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\end{eqnarray}
</td>
<td>
\begin{eqnarray}
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}
</td>
</tr>
</table>
Markdown cells are rendered so you don't see the code that generates the rendered latex. Instead you just see the rendered version until you double click it.
Plus you have the option of Markdown tables
I want to number gathered equations, but single number for several equations. Following is the code I've used. But it results numbering both equations. I want to equations to be justified, not right aligned. Spilt and align environment right align the equations. Is there any way to do this?
\begin{gather}
\eta_{c1} P_{pv}(k) + \eta_{c2} P_{bat}(k) \leq P_{conG,rate} \\\
P_{grid} + P_{load} \geq -P_{conG,rate}
\end{gather}
After \ you can put \nonumber this way you can avoid having both equations numbered
As said by Good Luck, you can add \nonumber at the end of the line before \\.
A problem I encountered was that when adding a \label{label_name} the Eq.~\ref{label_name} showed as (for example) Eq.2.5 instead of Eq.2. I've managed to sort this by moving the \label{label_name} to the row below \begin{gather}. So for example my code would look like this:
\begin{gather}
\label{labe_name}
e=\sum_{n=0}^{\infty}{\frac{1}{n!}}\\
\begin{aligned}
&\textit{\small Where:}\nonumber\\
&\textit{\small $1^{st}$ line and more explanations to fill the line} \nonumber\\
&\textit{\small $2^{nd}$ line}\nonumber\\
&\textit{\small ext \dots}\nonumber\\
\end{aligned}
\end{gather}
Make sure to have this packages:
\usepackage{amsmath,amssymb}
Here is a cleaner solution than using \nonumber. Using gathered or aligned environments inside an equation environment groups the equations and assigns one number to them. This is recommended by the amsmath user guide.
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{equation}
\begin{gathered}
\eta_{c1} P_{pv}(k) + \eta_{c2} P_{bat}(k) \leq P_{conG,rate}
\\
P_{grid} + P_{load} \geq -P_{conG,rate}
\end{gathered}
\end{equation}
\begin{equation}
\begin{aligned}
\eta_{c1} P_{pv}(k) + \eta_{c2} P_{bat}(k) &\leq P_{conG,rate}
\\
P_{grid} + P_{load} &\geq -P_{conG,rate}
\end{aligned}
\end{equation}
\end{document}
I am creating a document in LateX and the following multivalued function has been giving me trouble for a while.
The Latex code for the above as I gave is
$\[delta \tau_{i,j}^{k}$ = $\left\{$
\begin{array}{l l}
\frac{1}{L_{k}} & \quad \mbox{if ant k travels on edge \textit{i,j}} \\
0 & \quad \mbox{otherwise}
\end{array} \right. \]
While compiling it gives me the following error
! LaTeX Error: Bad math environment delimiter.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.52 $\[
delta \tau_{i,j}^{k}$ = $\left\{$
?
Any help on fixing this error would be much appreciated.
aschepler is right--it's the [ inside the $.
You may also want to consider the cases environment, which I think is easier for this sort of thing. For you example, you'd have:
\[
\Delta\tau_{i,j}^k=
\begin{cases}
1/L_k & \text{if ant $k$ travels along edge $i,j$} \\
0 & \text{otherwise}
\end{cases}
\]
You can't use both $ $ and \[ \] like that. $ is for in-line equations (fit within a paragraph of text), so you should probably use just \[ \] around your equation and remove all the $s.
I'm trying to learn LaTeX, currently because otherwise, my professors will be nearly unable to read my homework assignments. I've come across something I want to do, but don't seem to be able to, ie. I have searched google (possibly with a poor keyword set) and not found a solution.
The specific case is as follows: I want to put an ams flalign environment inside a box and have multiple such environments side by side. I have achieved this using minipage, but minipage asks for a width. I would like to use the smallest width in which the flalign environment fits. I realize that I can set the width to 0pt, but I can't help wondering if there's something that is intended to do this.
Also, should I be using minipage? Is there another command I don't know?
Thanks for your reply.
EDIT:
An attempted clarification as to what I want to do. I want equations which are standard, known, given, etc. and short on the left. To the right of those, I want relevant derived equations (and maybe their derivations. Further right, I want actual calculations plugged in.
I feel like what I want is a tabular environment with 3 columns, but I don't think I can put an equation environment in a tabular environment.
This looks like what I want when I render it.
\begin{minipage}[t]{0pt}
\begin{flalign*}
\sigma & = F / A&\\
A & = \pi \left(d/2\right)^2&\\
\epsilon &= \frac{\sigma}{E}&\\
\epsilon_{trans} &= - \nu \epsilon_{longi}& \\
\epsilon &= \frac{\Delta l}{l}&\\
l &= \left( \epsilon + 1 \right) \times l_0&
\end{flalign*}
\end{minipage}
\hspace*{0pt}
\begin{minipage}[t]{0pt}
\begin{flalign*}
d & = \unit[1.8]{mm} = \unit[1.8\e{-3}]{m} &\\
F_T & = \unit[1300]{N}&\\
E_{\text{stainless steel}}&=\unit[193\e9]{Pa}&\\
l_0 & = \unit[.2530]{m}&\\
\nu & = .33&\\
\sigma &= \frac{\unit[1300]{N}}{\pi \times \unit[3.24\e{-6}]{m^2}}&&= \boxed{\unit[127.7\e6]{Pa}}\\
&&&=\boxed{\unit[18,524]{psi}}\\
\epsilon &= \frac{\unit[127.7\e6]{Pa}}{\unit[193\e9]{Pa}} &&= \boxed{6.6\e{-2}}\\
\epsilon_{trans} &= -.33 \times 6.6\e{-2} &&=\boxed{-2.2\e{-2}}\\
l &= \left( 6.6\e{-2} + 1 \right) \times \unit[.2530]{m} &&= \boxed{\unit[.2797]{m}}
\end{flalign*}
\end{minipage}
I'm not sure exactly what you're trying to achieve, but amsmath's align* environment might do what you want (without resorting to minipages):
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{align*}
x&=y & X&=Y & a&=b+c & mn&=ab\\
x’&=y’ & X’&=Y’ & a’&=b & m'n'&=a'b'\\
x+x’&=y+y’ & X+X’&=Y+Y’ & a’b&=c’b & m'&=a'
\end{align*}
\end{document}
As to your minipage question: it requires a width because TeX needs to know where to break the lines. If you don't want the line-breaking algorithm to be used, you probably don't want a minipage.
Edit:
If you want multiple columns and don't care about the vertical alignment of material across the columns, that can be obtained easily enough with the multicols package:
\documentclass{article}
\usepackage{multicols}
\usepackage{lipsum}% just for some example text
\begin{document}
% The * version allows the columns to have ragged bottoms.
% The argument 2 is the number of columns.
\begin{multicols*}{2}
\lipsum[1]% one paragraph of Lorem ipsum.. filler text
\vfil% fills the remainder of the column with white space
\columnbreak% force a column break
\lipsum[2]% another paragraph of text
\vfil% fills the remainder of the column with white space
\end{multicols*}
\end{document}
You might find something to help you in the empheq and mathtools packages. empheq allows you to box equations and mathtools should provide some useful environments for stacking them horizontally.