reference algorithm - PMOB/study-tex GitHub Wiki

アルゴリズム

\begin{algorithm}
  \caption{what this is}
  \label{alg:something}
\begin{algorithmic}
\Function{funcname}{arguments}
  \State $x \gets value$
  \While{$x < 10$}
    \State \Call{print}{x}
    \If{$x > 7$}
      \State break
    \EndIf
  \EndWhile
  \State \Return $x$
\EndFunction
\end{algorithmic}
\end{algorithm}

アルゴリズム記述(疑似コード)にはめちゃイケスーパーアルゴリズム環境があります。 需要は情報系にしかないかもしれないけど。

環境には色々ありますが、書きやすさの点から 疑似コードの記述にalgorithmic環境、ラップにalgorithm環境の使用をおすすめします。 algorithmic環境の使用にはalgorithmicxのインストールとalgpseudocodeパッケージの利用、 algorithm環境の使用にはalgorithmsのインストールalgorithmパッケージの利用が必要になります。

sudo tlmgr install algorithmicx
sudo tlmgr install algorithms

algorithmic環境ではシンボルを使って疑似コードを生成していきます。

シンボル 意味
\State ステートメント(式や文)
\Statex 行番号のないステートメント
\If{condition} 条件式。終端に\EndIfを要求する。\ElsIfや\Elseも利用可能
\For{condition} for文。conditionにはk=1,2,\ldotsとか入れる。終端に\EndForを要求する
\ForAll{condition} forall文。conditionにはイテラブルとか入れる。終端に\EndForを要求する
\While{condition} while文。終端に\EndWhileを要求する
\Repeat do-while文に近い。終端に\Until{condition}を要求する
\Loop 低級なループ。終端に\EndLoopを要求する
\Require アルゴリズムの条件。だいたい引数の範囲とか型とか書く
\Ensure アルゴリズムの保証。だいたい返り値の範囲とか型とか書く
\Function{funcname}{arguments} 関数。終端に\EndFunctionを要求する
\Procedure{funcname}{arguments} プロシージャ。終端に\EndProcedureを要求する
\Return return文。文なので\Stateに入れるときれいになります
\Call{funcname}{arguments} 関数呼び出し。文なので\Stateに入れるときれいになります
\Comment{comment} 補足説明。いじらないと右詰めで表示されます

相変わらずプリアンブルで色々弄れるのでドキュメントを読んでみてください。

利用例

  • "end"系命令の表示をなくす
  • 行番号表示
  • キャプションをいじる

疑似コードはlistings使ってるのでlistingsの設定が多少影響します。

あとは\listofalgorithmsコマンドを使えばアルゴリズムの目次を作成できます。 book系文書クラスを利用しているとき\frontmatterに入れるといい感じ。

今回はarticleですけど、名前弄るのを見せたいのでこんな感じに。

\documentclass[a4j]{jsarticle}
\usepackage{amsmath}
\usepackage{algorithm, algpseudocode}
\usepackage{here}


\makeatletter
\renewcommand{\ALG@name}{アルゴリズム}
\renewcommand{\listalgorithmname}{アルゴリズムの一覧}
\makeatother

% remove end sentences
\algtext*{EndWhile}
\algtext*{EndIf}

% renew symbol
\algrenewcommand\algorithmicrequire{\textbf{条件:}}
\algrenewcommand\algorithmicensure{\textbf{保証:}}

\newcommand{\abs}[1]{\lvert #1 \rvert}
\newcommand{\Break}{\textbf{break}}


\begin{document}
\listofalgorithms

\begin{algorithm}[H]
  \caption{$f(x)=y\ (:= const)$となるxを求めるニュートン法}
  \label{alg:newton}
  \begin{algorithmic}[1]
    \Require
      \Statex $yは実数定数$
    \Ensure
      \Statex $返り値は誤差error以内でf(x)=yとなる実数解x$
    \Function{newton}{y}
      \State $x \gets initial\ value$ \Comment{収束する適切な値を使用する}
      \While{$\abs{f(x) - y} > error$}
        \State $x_n \gets x - \dfrac{f(x) - y}{f'(x)}$
        \If{$\abs{x_n - x} < error$}
          \State \Break
        \EndIf
        \State $x \gets x_n$
      \EndWhile
      \State \Return $x$
    \EndFunction
  \end{algorithmic}
\end{algorithm}
\end{document}

algorithm