我正在尝试为蒙特卡洛汉密尔顿编写 Leapfrog 积分器,但我无法正确对齐每一行,请提供任何建议。
预期输出:
我的代码:
\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
您可能应该查看其中一个算法包,但是只需对现有算法包进行一些微小的更改,您就可以获得
\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}