latex|算法algorithm宏包和注意事项
LaTeX 中 algorithm
环境完整指南
在科研论文里,写清楚算法步骤通常需要用到 伪代码环境。最常见的选择有两个包:
algorithm2e
—— 功能最强大,适合期刊/学位论文algorithmicx
+algpseudocode
—— 更灵活、可定制,常用于会议模板
1️⃣ 常用包的选择
-
algorithm2e
\usepackage[ruled,vlined]{algorithm2e}
ruled
:算法标题在上方,并有横线vlined
:每行后加竖线(折线效果),用来表示语句块作用域linesnumbered
:为每一行添加行号- 提供
\KwIn
,\KwOut
,\For
,\If
,\While
等高阶命令 - 自带行号、自动缩进、美观
-
algorithmicx + algpseudocode
\usepackage{algorithm} \usepackage{algpseudocode}
algorithm
负责浮动体,类似 figure/tablealgpseudocode
提供命令,比如\State
,\If
,\For
- 优点:高度可控,适合需要精细排版的场景
2️⃣ 基本结构
algorithm2e
示例
\begin{algorithm}[!t]\SetAlgoLined\caption{Power Allocation Algorithm}\KwIn{User set $\mathcal{U}$, channel gains $h_u$, total power $P$}\KwOut{Optimal power allocation $\{p_u\}$}Initialize $p_u \gets 0$ for all $u$\;\For{each user $u \in \mathcal{U}$}{Compute priority weight $w_u$\;\If{$w_u > \text{threshold}$}{Allocate power $p_u \gets f(h_u, w_u)$\;}}\Return $\{p_u\}$
\end{algorithm}
algorithmicx + algpseudocode
示例
\begin{algorithm}[!t]
\caption{Power Allocation Algorithm}
\begin{algorithmic}[1]
\Require User set $\mathcal{U}$, channel gains $h_u$, total power $P$
\Ensure Optimal power allocation $\{p_u\}$\State Initialize $p_u \gets 0$ for all $u$
\For{each user $u \in \mathcal{U}$}\State Compute priority weight $w_u$\If{$w_u > \text{threshold}$}\State Allocate power $p_u \gets f(h_u, w_u)$\EndIf
\EndFor
\State \Return $\{p_u\}$
\end{algorithmic}
\end{algorithm}
3️⃣ 注意事项
🔹 (1) 包冲突问题
- 有些模板(如 IEEEtran)自带
algorithm
环境,可能会和algorithm2e
冲突 - 解决方法:如果用
algorithm2e
,建议\usepackage[linesnumbered,ruled,vlined]{algorithm2e}
并避免同时加载algorithmicx
🔹 (2) 算法位置控制
\begin{algorithm}[!t]
—— 强制浮动到页面顶部[!h]
—— 尽量放在当前位置[!b]
—— 底部
🔹 (3) 行号 & 标题规范
- 行号:
algorithm2e
用\SetAlgoNlRelativeSize{-1}
调整大小 - 标题:最好简洁,避免超过一行
- 如果论文模板要求“Algorithm 1: xxx”,需检查 期刊模板 是否自带样式
🔹 (4) 中英文混排
- 建议输入输出统一用
\KwIn
、\KwOut
,保持一致 - 中文论文里标题可写中文,但正文尽量保持英文变量与符号
🔹 (5) 长算法分页
algorithm2e
自带分页支持algorithmicx
需要加\usepackage{algcompatible}
来避免分页问题
🔹 (6) 折线(竖线)控制
- 在
algorithm2e
里,折线由vlined
选项决定 - 如果不想要折线,有两种方法:
全局关闭:在导言区去掉 vlined
\usepackage[ruled]{algorithm2e}
局部关闭:在某个算法内部用命令
\SetVline{false}
需要恢复时再写
\SetVline{true}
👉 这样你可以灵活决定:有的算法直观用折线表示作用域,有的算法则更简洁无竖线。
4️⃣ 小技巧
-
伪代码中写注释
\tcp{This is a comment in algorithm2e} % or \Comment{This is a comment in algpseudocode}
-
多行输入/输出
\KwIn{$\mathcal{U}$: set of users, $P$: total power} \KwOut{Optimal allocation $\{p_u\}$}
-
强制换行
在algorithm2e
里用\;