Chapter 11 – Using LaTeX in Science and Technology

Here are the Code examples of this chapter. You can compile them online right on this web page by pressing the Typeset / Compile button. You can also edit them for testing and compile them again.

The code pages here are partially based on the First Edition of the book and are currently being edited to match the code of the Second Edition with all the additional examples. It is not complete yet since the focus was on the book production until days ago; please visit again soon!

Here are the Code examples of of this chapter. You can compile them online right on this web page by pressing the Typeset / Compile button. You can also edit them for testing, and compile again.

For a better view with the online compiler, I sometimes use \documentclass[border=10pt]{standalone} instead of \documentclass{article}. Instead of having a big letter/A4 page, the standalone class crops the paper to see just the visible text without an empty rest of a page.

Any question about a code example? Post it on LaTeX.org, I will answer. As forum admin I read every single question there. (profile link).

\documentclass{article}
\usepackage{dsfont}
\usepackage{mathtools}
\usepackage{algorithm}
\usepackage{algorithmicx}
%\usepackage{algpascal}
\usepackage{algpseudocode}
\algnewcommand{\Local}{\State\textbf{local variables: }}
\newcommand{\Let}[2]{\State $\mathmakebox[1em]{#1} \gets #2$}
\pagestyle{empty}
\begin{document}
%\listofalgorithms
\begin{algorithm}
  \caption{Mandelbrot set}
  \label{alg:mandelbrot}
  \begin{algorithmic}[1]
    \Require{$c_x, c_y, \Sigma_{\max} \in \mathds{R},
      \quad i \in \mathds{N}, \quad i_{\max} > 0,
      \quad \Sigma_{\max} > 0$}
    \Function{mandelbrot}{$c_x, c_y, i_{\max},
              \Sigma_{\max}$}
      \Local{$x, y, x_1, y_1, i, \Sigma$}
      \State $x, y, i, \Sigma \gets 0$
      \Comment{initial zero value for variables}
      \While{$\Sigma \leq \Sigma_{\max}$
             and $i < i_{\max}$}
        \Let{x_1}{x^2 - y^2 + c_x}
        \Let{y_1}{2xy + c_y}
        \Let{x}{x_1}
        \Let{y}{y_1}
        \Let{\Sigma}{x^2 + y^2}
      \EndWhile
      \If{$i < i_{\max}$}
        \State \Return{$i$}
      \EndIf
      \State \Return{0}
    \EndFunction
  \end{algorithmic}
\end{algorithm}
\end{document}

\documentclass[border={10pt 10pt 30pt 10pt}]{standalone}
\usepackage{xcolor}
\usepackage{inconsolata}
\newcommand{\Cpp}{C\texttt{++}}
\usepackage{listings}
\lstset{
  language     = C++,
  basicstyle   = \ttfamily,
  keywordstyle = \color{blue}\textbf,
  commentstyle = \color{gray},
  stringstyle  = \color{green!70!black},
  stringstyle  = \color{red},
  columns      = fullflexible,
  numbers      = left,
  numberstyle  = \scriptsize\sffamily\color{gray},
  caption      = A hello world program in \Cpp,
  xleftmargin  = 0.16\textwidth,
  xrightmargin = 0.16\textwidth,
  showstringspaces = false,
  float,
}
\begin{document}
\begin{lstlisting}
// include standard input/output stream objects:
#include 
// the main method:
int main()
{
    std::cout << "Hello TeX world!" << std::endl;
}
\end{lstlisting}
\end{document}

% !TEX lualatex
\documentclass[border=10pt]{standalone}
\usepackage{luacode}
\begin{document}
The value of $\sqrt{2}$ is \approx
\begin{luacode}
  local x = 1
  for i=1,10 do
    x = (x + 2/x)/2
  end
  tex.print(x)
\end{luacode}
\end{document}
% !TEX lualatex
\documentclass[border=10pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{width=7cm, compat=1.18}
\usepackage{luacode}
\begin{luacode}
  function mandelbrot(cx, cy, imax, smax)
    local x, y, x1, y1, i, s
    x, y, i, s = 0, 0, 0, 0
    while (s <= smax) and (i < imax)  do
      x1 = x * x - y * y + cx
      y1 = 2 * x * y + cy
      x = x1
      y = y1
      i = i + 1
      s = x * x + y * y
    end
    if (i < imax) then
      tex.print(i)
    else
      tex.print(0)
    end
  end
\end{luacode}
\begin{document}
\begin{tikzpicture}
  \begin{axis}[
    colorbar,
    point meta max = 30,
    tick label style = {font=\tiny},
    view={0}{90}]
    \addplot3 [surf, domain = -1.5:0.5, shader = interp,
               domain y = -1:1, samples = 150]
        { \directlua{mandelbrot(\pgfmathfloatvalueof\x,
          \pgfmathfloatvalueof\y,5000,4)} };
  \end{axis}
\end{tikzpicture}
\end{document}

\documentclass{standalone}
\usepackage{tkz-graph}
\GraphInit[vstyle = Shade]
\tikzset{
  LabelStyle/.style = { rectangle, rounded corners, draw,
                        minimum width = 2em, fill = yellow!50,
                        text = red, font = \bfseries },
  VertexStyle/.append style = { inner sep=5pt,
                                font = \Large\bfseries},
  EdgeStyle/.append style = {->, bend left} }
\thispagestyle{empty}
\begin{document}
\begin{tikzpicture}
  \SetGraphUnit{5}
  \Vertex{B}
  \WE(B){A}
  \EA(B){C}
  \Edge[label = 1](A)(B)
  \Edge[label = 2](B)(C)
  \Edge[label = 3](C)(B)
  \Edge[label = 4](B)(A)
  \Loop[dist = 4cm, dir = NO, label = 5](A.west)
  \Loop[dist = 4cm, dir = SO, label = 6](C.east)
  \tikzset{EdgeStyle/.append style = {bend left = 50}}
  \Edge[label = 7](A)(C)
  \Edge[label = 8](C)(A)
\end{tikzpicture}
\end{document}

\documentclass[border=15pt]{standalone}
\usepackage{tkz-graph}
\begin{document}
\begin{tikzpicture}[rotate=18]
  \SetGraphUnit{5}
  \GraphInit[vstyle=Normal]
  \Vertices{circle}{A,B,C,D,E}
  \Edges(A,B,C,D,E,A,D,B,E,C,A)
\end{tikzpicture}
\end{document}

% Bad example of using units
\documentclass[border=10pt]{standalone}
\begin{document}
% bad style which shall be improved:
\( m \cdot s = m \cdot 1 m s^{-1} \)
\end{document}

% Better way of using units
\documentclass[border=10pt]{standalone}
\usepackage{siunitx}
\begin{document}
\( m \cdot s = m \cdot \SI{1}{\meter\per\second} \)
\end{document}

\documentclass[border=10pt]{standalone}
\usepackage{siunitx}
\usepackage{cancel}
\usepackage{color}
\sisetup{per-mode = symbol}
\begin{document}
\( m \cdot s = m \cdot
  \SI{1e-3}{\cancel\m\highlight{red}\km\per\s} \)
\end{document}

\documentclass[border=10pt]{standalone}
\usepackage{siunitx}
\sisetup{per-mode = symbol}
\begin{document}
\( m \cdot s = m \cdot \SI{1}{\m\per\s} \)
\end{document}

\documentclass[border=10pt]{standalone}
\usepackage{siunitx}
\sisetup{per-mode = symbol}
\begin{document}
\si{\kg\m\per\square\s}
\end{document}

\documentclass[border=10pt]{standalone}
%\renewcommand{\familydefault}{\sfdefault}
\usepackage{siunitx}
\usepackage{sfmath}
\sisetup{per-mode = symbol, detect-all}
\begin{document}
\sffamily
\( m \cdot s = m \cdot \SI{1}{\m\per\s} \)
\end{document}

\documentclass{scrartcl}
\usepackage{chemformula}
\pagestyle{empty}
\begin{document}
\section*{About \ch{Na2SO4}}
\ch{Na2SO4} is sodium sulfate.
It contains \ch{Na+} and \ch{SO4^2-}.
\ch{Na2SO4 * 10 H2O} is a decahydrate.
\[
\ch{Na2SO4 + 2 C -> Na2S + 2 CO2}
\]
\begin{equation}
\ch{Na2SO4 + H2SO4 <=> 2 NaHSO4}
\end{equation}
\section*{Isotopes}
\ch{^{232}_{92}U140} is uranium-232.
\section*{Hydrocarbons}
\begin{itemize}
  \item \ch{H3C-CH3} is ethane,
  \item \ch{H2C=CH2} is ethylene,
  \item \ch{H2C+CH2} is ethyne.
\end{itemize}
\end{document}

\documentclass[border=10pt]{standalone}
\usepackage{chemfig}
\begin{document}
\renewcommand{\arraystretch}{1.5}
\begin{tabular}{rl}
  Hydrogen: & \chemfig{H-H} \\
  Oxygen:   & \chemfig{O=O} \\
  Ethyne:   & \chemfig{H-C~C-H}
\end{tabular}
\qquad
Methane: \chemfig{[,0.8]C(-[2]H)(-[4]H)(-[6]H)-H}
\end{document}

\documentclass[border=15pt]{standalone}
\usepackage{chemfig}
\begin{document}
\chemfig{C*6((-H)-C(-H)=C(-H)-C(-H)=C(-H)-C(-H)=)}
\end{document}

\documentclass[border=15pt]{standalone}
\usepackage{chemfig}
\begin{document}
\chemname{\chemfig{*6(=-=-=-)}}{Benzene}
\end{document}

\documentclass{article}
\usepackage{chemfig}
\pagestyle{empty}
\begin{document}
\chemfig{C*6((-H)-C(-H)=C(-H)-C(-H)=C(-H)-C(-H)=)}
\end{document}

\documentclass[border=15pt]{standalone}
\usepackage{chemfig}
\begin{document}
\definesubmol{C}{-C(-[2]H)(-[6]H)}
\chemfig{H!C!C!C!C!C-H}
\end{document}

\documentclass{article}
\usepackage{chemfig}
\pagestyle{empty}
\begin{document}
\chemfig[scale=1.5,transform shape][color=blue]{H-C~C-H}
\hspace{0.2\linewidth}
\chemfig[thick][rotate=15]{C(-[2]H)(-[4]H)(-[6]H)-H}
\end{document}

\documentclass[border=10pt]{standalone}
\usepackage{chemfig}
\newcommand{\charge}[1]{\rlap{${}^{\texttt{#1}}$}}
\newcommand{\positive}{\charge{+}}
\newcommand{\negative}{\charge{-}}
\begin{document}
\chemfig{H\positive-[:322.25]O\negative-[:37.75]H\positive}
\end{document}

\documentclass{article}
\usepackage[hmargin=4cm]{geometry}
\usepackage{carbohydrates}
\pagestyle{empty}
\begin{document}
\centering
\glucose[model=fischer,chain]\quad
\glucose[model={fischer=skeleton},chain]

\vspace{1cm}
\glucose[model=haworth,chain]\hfill
\glucose[model=haworth,ring]\hfill
\glucose[model=chair,ring]
\end{document}

\documentclass{article}
\usepackage[hmargin=4cm]{geometry}
\usepackage{carbohydrates}
\pagestyle{empty}
\begin{document}
\centering
\glucose[model=fischer,chain]\qquad
\glucose[model={fischer=skeleton},chain]
\end{document}

\documentclass{article}
\usepackage[hmargin=4cm]{geometry}
\usepackage{carbohydrates}
\pagestyle{empty}
\begin{document}
\centering
\glucose[model=haworth,chain]\hfill
\glucose[model=haworth,ring]\hfill
\glucose[model=chair,ring]
\end{document}

\documentclass[border=10pt]{standalone} 
\usepackage{tikz}
\usetikzlibrary{circuits.ee.IEC}
\begin{document}
\begin{tikzpicture}[
    circuit ee IEC,
    x = 3cm, y = 2cm,
    every info/.style = {font = \scriptsize},
    set diode graphic = var diode IEC graphic,
    set make contact graphic = var make contact IEC graphic,
  ]
  \foreach \i in {1,...,3} {
    \node [contact] (lower contact \i) at (\i,0) {};
    \node [contact] (upper contact \i) at (\i,1) {};
  }
  \draw (upper contact 1) to [diode] (lower contact 1);
  \draw (lower contact 2) to [capacitor] (upper contact 2);
  \draw (upper contact 1) to [resistor = {ohm = 6}]
        (upper contact 2);
  \draw (lower contact 2) to [resistor = {adjustable}]
        (lower contact 3);
  \draw (lower contact 1) to [
           voltage source = {near start,
                             direction info = {volt = 12}},
           inductor = {near end}]
        (lower contact 2);
  \draw (upper contact 2) to [make contact = {near start},
                              battery = {near end,
                                         info = {loaded}}]
        (upper contact 3);
  \draw (lower contact 3) to [bulb = {minimum height = 0.6cm}]
        (upper contact 3);
\end{tikzpicture}
\end{document}

Go to next chapter.