【实用技巧】Latex写算法伪代码(格式篇)

本文主要介绍个人在编写Latex算法伪代码时所遇到的格式问题。

包冲突

\usepackage{algorithm}  
\usepackage{algorithmic}  
\usepackage{algorithmicx}
\usepackage{algpseudocode}  

网上查找算法伪代码第三方包,主要会跳出来这四个库。但事实上这些包之间存在一些命名上的冲突,\usepackage{algorithmic}\usepackage{algorithmicx} 在方法上会有大小写的要求差异,如果调用了\usepackage{algorithmic},那么你的方法需要全部用大写字母表示,例如

\STATE

\FOR{
    
    ...}
\ENDFOR

如果同时调用这些包,则会在编译的时候出现报错:

在这里插入图片描述
这时候最简单的方式就是,注释掉冲突包:

\usepackage{
    
    algorithm}  
\usepackage{
    
    algorithmic}  
%\usepackage{
    
    algorithmicx}
%\usepackage{
    
    algpseudocode}  

换行与缩进

  • 换行使用\STATE单起一行即可
  • 缩进可以使用\qquad

例子

\begin{
    
    breakablealgorithm}
	\caption{
    
    YOLOv8 model}
	\begin{
    
    algorithmic}[6]
		
		\STATE Initialize YOLOv8 Network (Darknet or other backbone)
		\STATE \qquad Initialize SE, CBAM, SOCA attention modules
		\STATE
		\FOR{
    
    epoch in 1...N}
		\FOR{
    
    batch in DataLoader}
		\STATE images, ground\_truths = batch
		\ENDFOR
		\ENDFOR
		\STATE
	\end{
    
    algorithmic}
\end{
    
    breakablealgorithm}

编译结果:

在这里插入图片描述


算法换页

有些时候,LaTeX中的算法伪代码很长需要跨页展示,如下如图所示:

在这里插入图片描述
我们只需要在\begin{document}之前定义breakablealgorithm环境,代码如下

\makeatletter
\newenvironment{
    
    breakablealgorithm}
  {
    
    % \begin{
    
    breakablealgorithm}
   \begin{
    
    center}
     \refstepcounter{
    
    algorithm}% New algorithm
     \hrule height.8pt depth0pt \kern2pt% \@fs@pre for \@fs@ruled
     \renewcommand{
    
    \caption}[2][\relax]{
    
    % Make a new \caption
       {
    
    \raggedright\textbf{
    
    \ALG@name~\thealgorithm} ##2\par}%
       \ifx\relax##1\relax % #1 is \relax
         \addcontentsline{
    
    loa}{
    
    algorithm}{
    
    \protect\numberline{
    
    \thealgorithm}##2}%
       \else % #1 is not \relax
         \addcontentsline{
    
    loa}{
    
    algorithm}{
    
    \protect\numberline{
    
    \thealgorithm}##1}%
       \fi
       \kern2pt\hrule\kern2pt
     }
  }{
    
    % \end{
    
    breakablealgorithm}
     \kern2pt\hrule\relax% \@fs@post for \@fs@ruled
   \end{
    
    center}
  }
\makeatother

在此之后,将\begin{algorithm}\end{algorithm}替换成
\begin{breakablealgorithm}\end{breakablealgorithm}, 例如

\begin{
    
    breakablealgorithm}
	\caption{
    
    YOLOv8 model}
	\begin{
    
    algorithmic}[5]
		
		\STATE Initialize YOLOv8 Network (Darknet or other backbone)
		\STATE Initialize SE, CBAM, ECA, CA, and SOCA attention modules
		\STATE
		\FOR{
    
    epoch in 1...N}
		\FOR{
    
    batch in DataLoader}
		\STATE images, ground\_truths = batch
		
		\ENDFOR
		\ENDFOR
		\STATE
		\STATE // End of one epoch
		\STATE Validate\_on\_ValidationSet()
	\end{
    
    algorithmic}
\end{
    
    breakablealgorithm}

猜你喜欢

转载自blog.csdn.net/cold_code486/article/details/133954542
今日推荐