答案1
以下是一个起点,使用algorithm2e
:
\documentclass{article}
\usepackage{xcolor,amsmath}
\usepackage[linesnumbered,ruled,vlined]{algorithm2e}
\DontPrintSemicolon
% Define pseudocode formatting
\renewcommand{\KwSty}[1]{\textnormal{\textcolor{blue!90!black}{\ttfamily\bfseries #1}}\unskip}
\renewcommand{\ArgSty}[1]{\textnormal{\ttfamily #1}\unskip}
\SetKwComment{Comment}{\color{green!50!black}// }{}
\renewcommand{\CommentSty}[1]{\textnormal{\ttfamily\color{green!50!black}#1}\unskip}
\newcommand{\assign}{\leftarrow}
\newcommand{\var}{\texttt}
\newcommand{\FuncCall}[2]{\texttt{\bfseries #1(#2)}}
\SetKwProg{Function}{function}{}{}
\renewcommand{\ProgSty}[1]{\texttt{\bfseries #1}}
\begin{document}
\begin{algorithm}
\caption{Dynamic PCA}
\Comment{$\theta_{\mathrm{exp}}$ is globally given, and initially set to $\infty$.}
\Function{ExpandBasisIfInteresting($B$, $\Sigma$, $\vec{x}$)}{
\If{$\var{loss} > \theta_{\mathrm{exp}}$}{
$\var{loss} \assign \sqrt{\lVert \vec{x} \rVert^2 - \lVert \vec{x}^T B \rVert^2}$
\Comment{By Pythagoras}
$B, \Sigma \assign \FuncCall{Append}{$B$, $\Sigma$, $\vec{x}$}$\;
$B \assign \FuncCall{GramSchmidt}{$B$}$\;
}
$\theta_{\mathrm{exp}} \assign \FuncCall{UpdateLoss}{$\theta_{\mathrm{exp}}$, \var{loss}}$\;
\Return{$B$, $\Sigma$}\;
}
\Function{PeriodicDecompose($B$, $\Sigma$)}{
\If{\FuncCall{IsOneMinutePassed}{}}{
$B, \Sigma \assign \FuncCall{PCA}{$B$, $\Sigma$}$\;
}
\Return{$B$, $\Sigma$}\;
}
\Comment{The main function}
\Function{DynPCA($B$, $\Sigma$, $\vec{x}$, $s$)}{
$B, \Sigma \assign \FuncCall{ExpandBasisIfInteresting}{$B$, $\Sigma$, $\vec{x}$}$\;
$\Sigma \assign \FuncCall{UpdateCovMatrix}{$B$, $\Sigma$, $\vec{x}$, $s$}$\;
$B', \Sigma' \assign \FuncCall{PeriodicDecompose}{$B$, $\Sigma$}$\;
\Return{$B'$, $\Sigma'$}
}
\end{algorithm}
\end{document}
答案2
algorithm2e 包提供上述功能(不是默认的,但它是相当可定制的)。