算法环境问题

算法环境问题

我正在做我的硕士论文,需要将一个算法纳入我的 LaTeX 代码中。我已经尝试了几个小时,但仍然有几个错误总是出现。这是我第一次使用该algorithm软件包,所以如果能得到帮助我将不胜感激。以下是代码:

\documentclass{article}
\usepackage{algorithm,algorithmic,algpseudocode}
\begin{document}
\begin{algorithm}
\caption{Resource Allocation Algorithm }
\label{alg:algorithm_sum}
\begin{algorithmic}[1]
\State{Initialization of maximum number of iteration $I_{\text{max}}$, given $\mu^m$ and $\beta^m$ and obtain the intermediate solution for (opt. variables)} 
\If{ref. is satisfied} 
\State{Convergence =  true} 
\Return{opt. variables} 
\Else 
\State{update $\mu$ and $\beta$ according to ref. and $m=m+1$} 
\State{Convergence =  false} 
\EndIf
\Until{Convergence = true or $m=I_{\text{max}}$} 
\end{algorithmic}
\end{algorithm}
\end{document}

答案1

首先,您正在加载不兼容的algorithmicalgpseudocode(的变体)。algorithmicx

您使用的语法是algpseudocodeso don't load algorithmic。此外,您正在使用\textand forgot to load amsmath

最后,\Until必须使用该命令来关闭\Repeat代码中缺少的语句。

这是您修改后的 MWE \Repeat(将其移动到算法中的正确位置):

\documentclass{article}
\usepackage{amsmath}
\usepackage{algorithm,algpseudocode}
\begin{document}
\begin{algorithm}
\caption{Resource Allocation Algorithm }
\label{alg:algorithm_sum}
\begin{algorithmic}[1]
\State{Initialization of maximum number of iteration $I_{\text{max}}$, given $\mu^m$ and $\beta^m$ and obtain the intermediate solution for (opt. variables)}
\Repeat
\If{ref. is satisfied}
\State{Convergence =  true}
\Return{opt. variables}
\Else
\State{update $\mu$ and $\beta$ according to ref. and $m=m+1$}
\State{Convergence =  false}
\EndIf
\Until{Convergence = true or $m=I_{\text{max}}$}
\end{algorithmic}
\end{algorithm}
\end{document} 

输出:

在此处输入图片描述

答案2

另一种可能性是保留algorithmic并删除algpseudocode以消除不兼容性。但语法略有改变,如下所示:

\documentclass{article}
\usepackage{amsmath,algorithm,algorithmic}
\begin{document}

\begin{algorithm}
\caption{Resource Allocation Algorithm }
\label{alg:algorithm_sum}
\begin{algorithmic}[1]
\STATE{Initialization of maximum number of iteration $I_{\text{max}}$, given $\mu^m$ and $\beta^m$ and obtain the intermediate solution for (opt. variables)} 
\REPEAT
\IF{ref. is satisfied} 
\STATE{Convergence =  true} 
\RETURN{opt. variables} 
\ELSE 
\STATE{update $\mu$ and $\beta$ according to ref. and $m=m+1$} 
\STATE{Convergence =  false} 
\ENDIF
\UNTIL{Convergence = true or $m=I_{\text{max}}$} 
\end{algorithmic}
\end{algorithm}

\end{document}

在此处输入图片描述

还请注意,您可以修改算法,因为until通常需要repeat关闭。您可以根据需要进行更改。

相关内容