algorithm2e で方程式を使用するときに作成される追加の行

algorithm2e で方程式を使用するときに作成される追加の行

equation*環境内に sを配置する次の例を考えてみましょうalgorithm

\documentclass{standalone}

\usepackage{amsmath}
\usepackage{algorithm2e}

\LinesNumbered

\begin{document}
\begin{algorithm}[H]
  \SetAlgoLined
  \KwData{this text}
  \KwResult{how to write algorithm with \LaTeX2e }
  \ForEach{first loop} {
    \begin{equation*}
      a^2 + b^2 = c^2
    \end{equation*}
    After \;
    After \;
    After \;
  }
  \ForEach{second loop} {
    Before
    \begin{equation*}
      a^2 + b^2 = c^2
    \end{equation*}
    After \;
    After \;
    After \;
  }
  \caption{How to write algorithms}
\end{algorithm}
\end{document}

これにより、次の出力が生成されます。

出力

問題は、数式の間隔です。具体的には、2 行目には、必要のない垂直方向のスペースが大量に追加されています。実際、7 行目を見ると、レイアウトに残っている空白スペース内で、数式が始まる前にテキストを追加できることがわかります。さらに、2 行目は数式と揃うのではなく、数式の上にあります。

方程式をより自然に動作させ、追加のスペースの導入を回避する方法はありますか?

答え1

クイックハック:

\documentclass{standalone}

\usepackage{amsmath}
\usepackage{algorithm2e}

\LinesNumbered

\begin{document}
\begin{algorithm}[H]
  \SetAlgoLined
  \KwData{this text}
  \KwResult{how to write algorithm with \LaTeX2e }
  \ForEach{first loop} {
    \parbox{\hsize}{%
      \[
      a^2 + b^2 = c^2
      \]
    }\par
    After \;
    After \;
    After \;
  }
  \ForEach{second loop} {
    Before\par
    \parbox{\hsize}{%
      \[
      a^2 + b^2 = c^2
      \]
    }\par
    After \;
    After \;
    After \;
  }
  \caption{How to write algorithms}
\end{algorithm}
\end{document}

ここに画像の説明を入力してください

答え2

特定の環境を定義します。

\documentclass{article}

\usepackage{amsmath}
\usepackage{algorithm2e}

\NewDocumentEnvironment{algoequation}{b}{%
  \par\makebox[\dimeval{\hsize}]{$\displaystyle#1$}\par
}{}


\LinesNumbered

\begin{document}
\begin{algorithm}[H]
  \SetAlgoLined
  \KwData{this text}
  \KwResult{how to write algorithm with \LaTeX2e }
  \ForEach{first loop} {
    \begin{algoequation}
      a^2 + b^2 = c^2
    \end{algoequation}
    After \;
    After \;
    After \;
  }
  \ForEach{second loop} {
    Before
    \begin{algoequation}
      a^2 + b^2 = c^2
    \end{algoequation}
    After \;
    After \;
    After \;
  }

\caption{How to write algorithms}
\end{algorithm}

\end{document}

ここに画像の説明を入力してください

簡単な変更を加えるだけで、固定インデントを実現できます。

\NewDocumentEnvironment{algoequation}{b}{%
  \par\hspace*{\algomargin}$\displaystyle#1$\par
}{}

ここに画像の説明を入力してください

このため、特定の環境を定義することをお勧めします。特定の表現に縛られることはなく、定義は簡単に変更できますが、ドキュメント コードは変更できません。

サイドノート。standaloneこのような例には使用しないでください。

関連情報