【问题标题】:What is the right way to insert an equation within a pseudo code在伪代码中插入方程式的正确方法是什么
【发布时间】:2015-12-11 02:56:12
【问题描述】:

我开始用 Latex 写笔记,并尝试根据这个等式编写伪代码:

这是我迄今为止尝试过的代码。

\begin{addmargin}[10mm]{0mm}
     \textbf{Repeat until convergence:} \ \{ 
     \[
         \theta_j := \theta_j + \alpha \sum_{i=1}^m(y^{(i)}-h_\theta(x^{(i)})) \ x_j^{(i)} \quad (\text{for every} \ j).
     \]
     \}
  \end{addmargin}

我还是觉得有点乱。你有更简单的方法来写这个吗?

【问题讨论】:

  • 有什么问题吗?如果没有,并且您想查看您的代码,请将其提交至codereview
  • 是的,仍然存在由于显示方程命令 [ ... ] 导致方程缩进的问题。正如您在附图中看到的那样,它看起来像一个缩进的等式,这与我们编写代码的方式相同。
  • @dfri 感谢您提醒我标记您的答案。我喜欢它。

标签: latex equation


【解决方案1】:

这个问题可能应该移到tex.stackexchange。


有几个不同的整洁的乳胶包专门用于编写伪代码。一种更简单的方法是使用Algorithmicx 包(包文档here),特别是其中的algpseudocode 部分。

这是使用 Algoritmicx 的伪代码的 MWE:

\documentclass{article}

\usepackage{amsmath}
\usepackage{algpseudocode}
\renewcommand{\algorithmicforall}{\textbf{for each}}

\begin{document}
\noindent Let $\mathcal{J} := \{1, ..., n\}$.

\begin{algorithmic}
    \While {Some convergence criteria is not fulfilled ...}
        \ForAll {$j \in \mathcal{J}$}
            \State $\theta_j \gets \theta_j + \alpha \sum_{i=1}^m(y^{(i)}-h_\theta(x^{(i)})) \ x_j^{(i)}$
        \EndFor   
        \State {... update some convergence measure} \Comment{Describe convergence measure}
    \EndWhile 
\end{algorithmic}

\end{document}

请注意,在第四个非空行,我重载了来自 algorithmicx (\algorithmicforall) 的 \ForAll 命令文本,变成“for ... each”而不是而不是“for ... all”。

还请注意,通常只有 cmets 可能包含伪代码文本,因此句子“某些收敛标准不满足 ...”和“...更新一些收敛度量” ”上面应该替换为您定义的算法/方程的收敛性。

【讨论】:

  • 谢谢。你的回答看起来比我预期的要正式一些,但我喜欢它。
【解决方案2】:

这就是你想要的,来自包algorithmalgorithmic

\begin{algorithm}
\caption{Gradient Descent}\label{alg-gd}
\begin{algorithmic}[1]
\STATE Initialize \( \theta_{0} = k\in \R^d \)
\STATE Initialize \( t \leftarrow 0 \)
\REPEAT
\STATE \( \forall j \in \{1,..., d\}, \theta_{j,t+1} \leftarrow \theta_{j,t} - \alpha \frac{\p }{\p \theta_{j} } L(\theta )\bigg|_{\theta = \theta_{t} }  \)
\STATE \( t \leftarrow t + 1 \)
\UNTIL{convergence}

给出,

注意:如果您在投影仪中使用它,请将\begin{algorithm}[H] 放在上面的行中,而不仅仅是\begin{algorithm}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    相关资源
    最近更新 更多