1

I'm trying to write the Leapfrog integrator for Monte Carlo Hamiltonian, but I can not properly align each of the rows, any suggestions please.

Expected Output:

enter image description here

My code:

\documentclass[12pt,a4paper]{article}
\usepackage{amsmath}

\begin{document}
\[
\boxed{
  \!\begin{aligned}
  \textbf{function} & \ LEAPFROG ((\boldsymbol{q}_0, \boldsymbol{p}_0); h, L) \\
    & \boldsymbol{p}_{1/2} \leftarrow  \boldsymbol{p}_0 - \frac{1}{2} h \nabla_q U(q_0) \\
    & \textbf{for} \  i \leftarrow 1,2,...,L \\
    & \boldsymbol{q}_i \leftarrow \boldsymbol{q}_{i-1} + h \boldsymbol{M}^{-1} \boldsymbol{p}_{i-1/2}\\
    & \textbf{if} \ i \neq L \ \textbf{then}\\
    & \boldsymbol{p}_{i + 1/2} \leftarrow \boldsymbol{p}_{i-1/2} - h \nabla_\boldsymbol{q} U (\boldsymbol{q}_i)\\
    & \boldsymbol{p}_L \leftarrow \boldsymbol{p}_{L-1/2} - 1/2 h \nabla_\boldsymbol{q} U (\boldsymbol{q}_L) \\
    & \textbf{return} \ ((\boldsymbol{q}_L, \boldsymbol{p_L}) \ \text{as} \ ((\boldsymbol{q}^*, \boldsymbol{p}^*)
  \end{aligned}
}
\]
\end{document}
1
  • 1
    Try to do that with dedicated packages, e.g. algorithms and algpseudocode packages. – Bernard Apr 22 '19 at 0:02
3

You should probably look at one of the algorithm packages, however with some minimal changes from what you have, you get

enter image description here

\documentclass[12pt,a4paper]{article}
\usepackage{amsmath}

\begin{document}
\[
\boxed{
  \begin{aligned}
  &\textbf{function} \ \textsc{Leapfrog}\  ((\boldsymbol{q}_0, \boldsymbol{p}_0); h, L) \\
    &\quad \boldsymbol{p}_{1/2} \leftarrow  \boldsymbol{p}_0 - \tfrac{1}{2} h \nabla_q U(q_0) \\
    &\quad \textbf{for} \  i \leftarrow 1,2,...,L \\
    &\qquad \boldsymbol{q}_i \leftarrow \boldsymbol{q}_{i-1} + h \boldsymbol{M}^{-1} \boldsymbol{p}_{i-1/2}\\
    &\qquad \textbf{if} \ i \neq L \ \textbf{then}\\
    &\quad\qquad \boldsymbol{p}_{i + 1/2} \leftarrow \boldsymbol{p}_{i-1/2} - h \nabla_{\boldsymbol{q}} U (\boldsymbol{q}_i)\\
    &\quad \boldsymbol{p}_L \leftarrow \boldsymbol{p}_{L-1/2} - 1/2 h \nabla_{\boldsymbol{q}} U (\boldsymbol{q}_L) \\
    &\quad \textbf{return} \ ((\boldsymbol{q}_L, \boldsymbol{p_L}) \ \text{as} \ ((\boldsymbol{q}^*, \boldsymbol{p}^*)
  \end{aligned}
}
\]
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.