Math & ScienceAlgorithm causes several Errors

Information and discussion about LaTeX's math and science related features (e.g. formulas, graphs).
Post Reply
APOCooter
Posts: 2
Joined: Thu Oct 17, 2013 4:05 am

Algorithm causes several Errors

Post by APOCooter »

I'm brand new to LaTeX so most errors are gibberish to me. I'm using the algorithme2e package and getting errors like this.

Code: Select all

You can't use '\prevdepth' in restricted horizontal mode.
\no interlineskp -> \prevdepth
Along come messages about inserting $, which I don't understand because I think I've put things in the proper environments.

Hopefully this is adequate as a MWE.

Code: Select all

\documentclass[letterpaper]{article}
\usepackage{amsmath}
\usepackage{algorithm2e}

\begin{document}
  The Laplace distribution has the CDF 
  \begin{equation*}F_x(x)=
    \begin{cases}
      \frac{\theta}{2}exp(\frac{x-\mu}{b}) & \text{if } x \leq \mu \\
      1-\frac{\theta}{2}exp(\frac{x-\mu}{b}) & \text{if } x > \mu
    \end{cases}
  \end{equation*}
  We can use the following algorithm to generate observations from the Laplace distribution using U~(0,1)
  \begin{algorithm}
    \SetAlgoLined
    \KwData[U~(0, 1)}
    \KwResult{Generate observations from the Laplace distribution}
    initialization\;
    \For{U~(0, 1)}{
      \eIf{u < 0.5}{
        \begin{equation*}
          x={ln(\frac{2u}{\theta}}{\theta}
        \end{equation*}
      }
      \eIf{u $\geq$ 0.5}{
        \begin{equation*}
          x=-\theta ln(\frac{2-2u}{\theta})
        \end{equation*}
      }
    }
    \caption{How to generate Laplace variables from U~(0, 1)}
  \end{algorithm} 
\end{document} 
Any help would be greatly appreciated.

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

Johannes_B
Site Moderator
Posts: 4182
Joined: Thu Nov 01, 2012 4:08 pm

Algorithm causes several Errors

Post by Johannes_B »

Hi, the eIF-macro takes 3 arguments

Code: Select all

\eIF{condition}{then block}{else block}
I don't know if the algorithm is right, but this works.

Code: Select all

    \documentclass[letterpaper]{article}
    \usepackage{amsmath}
    \usepackage{algorithm2e}

    \begin{document}
    \begin{algorithm}
    \SetAlgoLined
    \KwData{U~(0, 1)}
    \KwResult{Generate observations from the LaPlace distribution}
    %initialization\;
    \For{U~(0, 1)}{
    \eIf{u < 0.5}{
    $x={ln(\frac{2u}{\theta}}{\theta}$
    }{
    \eIf{u $\geq$ 0.5}{
    $x=-\theta ln(\frac{2-2u}{\theta})$
    }{}
    }}
    \caption{How to generate LaPlace variables from U~(0, 1)}
    \end{algorithm}
    \end{document} 
I changed the math to the inline form ($math$).

Best regards
Johannes

PS: I would count that as a quite good minimal example for a starter.
The smart way: Calm down and take a deep breath, read posts and provided links attentively, try to understand and ask if necessary.
Post Reply