Latex 如何写算法?推荐模板

之前我已经在这篇文章总结了现有的算法包的区别。如果有选择苦难症的朋友可以考虑无脑使用以下模板来写算法。


\usepackage[noend]{algpseudocode}  # noend表示算法不显示 EndIf或者EndFor这些,可以用来节省空间
\usepackage{algorithmicx}


\renewcommand{\algorithmicrequire}{\textbf{Input:}} # 将\Require命令显示成 Input:
\renewcommand{\algorithmicensure}{\textbf{Output:}} # 将\Ensure命令显示出 Output: ,你也可以自定义成其他的单词


\begin{algorithm}[!ht]
    \begin{algorithmic}[1]
        \Require{Epoch $E$, Dataset $D$, Model $M$, Loss function $\mathcal{L}$}
        \Ensure{Loss $l$}
    
        \Procedure{Main}{$E,D,M,\mathcal{L}$}
            \State $l=0 \leftarrow$ init loss value
            \For{e=1:$E$}
                \For{Mini-batch data $x$, label $y$ in $D$}
                    \State $z = M(x)$
                    \State $l +=  \mathcal{L}(z,y)$
            \EndFor
            \If{$l\leq 0.5$}
                \State \textbf(return) $l$
            \Else
                \State \textbf{return} $l-0.5$
            \EndIf
        \EndProcedure
    \end{algorithmic}
    \caption{Algorithm of Example}
    \label{alg:example_alg}
\end{algorithm}

效果如下图

image

更多语法可参考:https://texdoc.org/pkg/algorithmicx

posted @ 2022-09-29 16:54  marsggbo  阅读(1007)  评论(0)    收藏  举报