diff options
Diffstat (limited to 'macros/latex/contrib/numerica/numerica-basics.tex')
-rw-r--r-- | macros/latex/contrib/numerica/numerica-basics.tex | 4743 |
1 files changed, 4743 insertions, 0 deletions
diff --git a/macros/latex/contrib/numerica/numerica-basics.tex b/macros/latex/contrib/numerica/numerica-basics.tex new file mode 100644 index 0000000000..6e58e34822 --- /dev/null +++ b/macros/latex/contrib/numerica/numerica-basics.tex @@ -0,0 +1,4743 @@ +%% LyX 2.4.0-alpha1 created this file. For more info, see https://www.lyx.org/. +%% Do not edit unless you really know what you are doing. +\documentclass[english,tableposition=top]{report} +\usepackage{lmodern} +\renewcommand{\sfdefault}{lmss} +\renewcommand{\ttdefault}{lmtt} +\usepackage[T1]{fontenc} +\usepackage{textcomp} +\usepackage[utf8]{inputenc} +\setcounter{secnumdepth}{3} +\usepackage{color} +\definecolor{shadecolor}{rgb}{0.667969, 1, 1} +\usepackage{babel} +\usepackage{array} +\usepackage{cprotect} +\usepackage{wrapfig} +\usepackage{booktabs} +\usepackage{framed} +\usepackage{url} +\usepackage{amsmath} +\usepackage{amssymb} +\usepackage[unicode=true,pdfusetitle, + bookmarks=true,bookmarksnumbered=true,bookmarksopen=true,bookmarksopenlevel=2, + breaklinks=true,pdfborder={0 0 1},backref=section,colorlinks=true] + {hyperref} + +\makeatletter + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LyX specific LaTeX commands. +\providecommand{\LyX}{\texorpdfstring{\ensureascii{% + L\kern-.1667em\lower.25em\hbox{Y}\kern-.125emX\@}}{LyX}} +\DeclareRobustCommand*{\lyxarrow}{% +\@ifstar +{\leavevmode\,$\triangleleft$\,\allowbreak} +{\leavevmode\,$\triangleright$\,\allowbreak}} +%% Because html converters don't know tabularnewline +\providecommand{\tabularnewline}{\\} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands. +\newenvironment{centred}% + {\begin{center}\baselineskip=13pt\parskip=1pt}{\end{center}} +\newenvironment{lyxcode} + {\par\begin{list}{}{ + \setlength{\rightmargin}{\leftmargin} + \setlength{\listparindent}{0pt}% needed for AMS classes + \raggedright + \setlength{\itemsep}{0pt} + \setlength{\parsep}{0pt} + \normalfont\ttfamily}% + \item[]} + {\end{list}} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands. +\usepackage{numerica} + +\newcommand\rel{\,\varrho\;} +\DeclareMathOperator{\erf}{erf} +\DeclareMathOperator{\gd}{gd} + +\reuse + +\usepackage{upquote} + +\makeatother + +\begin{document} +\title{\texttt{numerica-basics}} +\author{Andrew Parsloe\\ +(\url{ajparsloe@gmail.com})\\ +} +\maketitle +\begin{abstract} +The \verb`numerica` package defines a command to wrap around a mathematical +expression in its LaTeX form and, once values are assigned to variables, +numerically evaluate it. The intent is to avoid the need to modify +the LaTeX form of the expression being evaluated. For programs with +a preview facility like LyX, or compile-as-you-go systems, interactive +back-of-envelope calculations and numerical exploration are possible +within the document being worked on. The package requires the bundles +\verb`l3kernel` and \verb`l3packages`, and the \verb`amsmath` and +\verb`mathtools` packages. Additional modules define commands to +iterate and find fixed points of functions of a single variable, to +find the zeros or extrema of such functions, to calculate the terms +of recurrence relations, and to create multi-column tables of function +values (which requires the \verb`booktabs` package).\\ +\\ +\noindent\begin{minipage}[t]{1\columnwidth}% +\begin{shaded}% + +\paragraph*{Note:} +\begin{itemize} +\item {\normalsize This document applies to version 1.0.0 of }{\normalsize\texttt{numerica.sty}}{\normalsize .}{\small\par} +\item {\normalsize Reasonably recent versions of the \LaTeX 3 bundles }{\normalsize\texttt{l3kernel}}{\normalsize{} +and }{\normalsize\texttt{l3packages}}{\normalsize{} are required.}{\small\par} +\item {\normalsize The package requires }{\normalsize\texttt{amsmath}}{\normalsize{} +and }{\normalsize\texttt{mathtools}}{\normalsize .}{\small\par} +\item {\normalsize I refer many times in this document (especially §\ref{sec:Argument-parsing}) +to }{\normalsize\emph{Handbook of Mathematical Functions}}{\normalsize , +edited by Milton Abramowitz and Irene A. Segun, Dover, 1965. This +is abbreviated to }{\normalsize\emph{HMF}}{\normalsize , often followed +by a number like 1.2.3 to locate the actual expression referenced.}{\small\par} +\end{itemize} +\end{shaded}% +\end{minipage} +\end{abstract} +\begin{center} +\tableofcontents{} +\par\end{center} + +\chapter{Introduction} + +\texttt{numerica} is a \LaTeX{} package offering the ability to numerically +evaluate mathematical expressions in the \LaTeX{} form in which they +are typeset.\footnote{\texttt{numerica} evolved from the author's \texttt{calculyx} package +that was designed for use with the document processor \LyX{} and available +for download from a link on the \LyX{} wiki website (but not from CTAN). } + +There are a number of packages which can do calculations in \LaTeX ,\footnote{A simple search finds the venerable \texttt{calc} in the \LaTeX{} base, +\texttt{calculator }(including an associated \texttt{calculus} package), +\texttt{fltpoint}, \texttt{fp} (\emph{fixed} rather than floating +point), \texttt{spreadtab} (using either \texttt{fp} or \texttt{l3fp} +as its calculational engine) if you want simple spreadsheeting with +your calculations, the elaborate \texttt{xint}, \texttt{pst-calculate} +(a limited interface to \texttt{l3fp}), \texttt{l3fp} in the \LaTeX 3 +kernel, and \texttt{xfp}, the \LaTeX 3 interface to \texttt{l3fp}. +Other packages include a calculational element but are restricted +in their scope. (\texttt{longdivision} for instance is elegant, but +limited only to long division.) } but those I am aware of all require the mathematical expressions +they operate on to be changed to an appropriate syntax. Of these packages +\texttt{xfp} comes closest to my objective with \texttt{numerica}. +For instance, given a formula +\begin{centred} +\verb`\frac{\sin (3.5)}{2} + 2\cdot 10^{-3}` +\end{centred} +(in a math environment), this can be evaluated using \texttt{xfp} +by transforming the expression to \verb`sin(3.5)/2 + 2e-3` and wrapping +this in the command \verb`\fpeval`. In \texttt{numerica} you don't +need to transform the formula, just wrap it in an \verb`\eval` command +(for the acutal calculation see §\ref{subsec:introSimple-examples}): +\begin{centred} +\verb`\eval{ \frac{\sin (3.5)}{2} + 2\cdot 10^{-3} }`. +\end{centred} +\texttt{numerica}, like \texttt{xfp} and a number of other packages, +uses \texttt{l3fp} (the \LaTeX 3 floating point module in \texttt{l3kernel}) +as its calculational engine. To some extent the main command, \verb`\nmcEvaluate`, +short-name form \verb`\eval`, is a pre-processor to \texttt{l3fp}, +converting mathematical expressions written in the \LaTeX\texttt{ +}form in which they will be typeset into an `fp-ified' form that +is digestible by \texttt{l3fp}. The aim is to make the command act +as a wrapper around such formulas. Ideally, one should not have to +make \emph{any} adjustment to them, although any text on Fourier series +suggests that hope in full generality is delusional. Surprisingly +often however it \emph{is} possible. We will see shortly that even +complicated formulas like + +\[ +\cos\tfrac{m}{n}\pi-(1-4\sin^{2}\tfrac{m}{3n}\pi)\frac{\sin\tfrac{1}{n}\pi\sin\tfrac{m-1}{n}\pi}{2\sin^{2}\tfrac{m}{3n}\pi}, +\] +and +\[ +\left(\frac{1-4\sin^{2}\tfrac{m}{3n}\pi}{2\sin^{2}\tfrac{m}{3n}\pi}\right)\sin\tfrac{2m-3}{3n}\pi\sin\tfrac{m-3}{3n}\pi, +\] + +\noindent can be evaluated `as is' (see below, §\ref{subsec:introReassurance}). +There is no need to shift the position of the superscript $2$ on +the sines, no need to parenthesize the arguments of $\sin$ and $\cos$, +no need to insert asterisks to indicate multiplication, no need to +change the \verb`\frac` and \verb`\tfrac`-s to slashes, \texttt{/}, +no need to delete the \verb`\left` and \verb`\right` that qualify +the big parentheses (in the underlying \LaTeX ) in the second expression. +Of course, if there are variables in an expression, as in these examples, +they will need to be assigned values. And how the result of the evaluation +is presented also requires specifying, but the aim is always: to evaluate +mathematical expressions in \LaTeX{} with as little adjustment as possible +to the form in which they are typeset. + +\texttt{numerica} is written in \texttt{expl3}, the programming language +of the \LaTeX 3 project. It uses the \LaTeX 3 module \texttt{l3fp} +(part of \texttt{l3kernel}) as its calculational engine. This enables +floating point operations to 16 significant figures, with exponents +ranging between $-10000$ and $+10000$. Many functions and operations +are built-in to \texttt{l3fp} – arithmetic operations, trigonometric, +exponential and logarithm functions, factorials, absolute value, max +and min. Others have been constructed for \texttt{numerica }from \texttt{l3fp} +ingredients – binomial coefficients, hyperbolic functions, sums and +products – but to the user there should be no discernible difference. + +Associated modules provide for additional operations: iteration, finding +zeros, recurrence relations, mathematical table building. Further +modules are planned (e.g. calculus). + +\section{How to use \texttt{numerica}} + +The package is invoked in the usual way:\footnote{I use the angle-bracket notation to indicate optional user input. +Of course what is input does not include the angle brackets.} put +\begin{lyxcode} +\textbackslash usepackage{[}<options>{]}\{numerica\} +\end{lyxcode} +\noindent in the \LaTeX{} preamble. \texttt{numerica} requires the +\texttt{amsmath} and \texttt{mathtools} packages and loads these automatically. +\texttt{numerica} will also accept use of some relational symbols +from the \texttt{amssymb} package provided that package is loaded; +see §\ref{subsec:evalBoolean-output}. + +\subsection{Packages and package options} + +\label{subsec:introPackagesOptions}Version 1.0.0 of \texttt{numerica} +has three package options. +\begin{description} +\item [{\texttt{plus}}] By calling \texttt{numerica} with the \texttt{plus} +package option,\\ +{\ttfamily{}% +\noindent\begin{minipage}[t]{1\columnwidth}% +~~~~\textbackslash usepackage{[}plus{]}\{numerica\}% +\end{minipage}}\texttt{}~\\ +the file \texttt{numerica-plus.def }is loaded where a number of additional +commands: \verb`\nmcIterate`, \verb`\nmcSolve`, \verb`\nmcRecur` +are defined. These enable the iteration of functions of a single variable\footnote{At this stage!}, +including finding fixed points; the solving of equations of the form +$f(x)=0$ (or the location of local maxima or minima); and the calculation +of terms in recurrence relations (like the Fibonacci series or othogonal +polynomials). See the associated document \texttt{numerica-plus.pdf}. +\item [{\texttt{tables}}] By calling \texttt{numerica} with the \texttt{tables} +package option\\ +{\ttfamily{}% +\noindent\begin{minipage}[t]{1\columnwidth}% +~~~~\textbackslash usepackage{[}tables{]}\{numerica\}% +\end{minipage}}\texttt{}~\\ +the file \texttt{numerica-tables.def} is loaded with with the command +\verb`\nmcTabulate` enabling the creation of multi-column tables +of function values with a wide variety of formatting options (most +of those employed in \emph{HMF} in fact). See the associated document +\texttt{numerica-tables.pdf}. +\item [{\texttt{lyx}}] By calling \texttt{numerica} with the \texttt{lyx} +package option,\\ +{\ttfamily{}% +\noindent\begin{minipage}[t]{1\columnwidth}% +~~~~\textbackslash usepackage{[}lyx{]}\{numerica\}% +\end{minipage}}\texttt{}~\\ +the file \texttt{numerica-lyx.def }is loaded with code enabling the +full use of the \verb`\nmcReuse` command in the document processor +\LyX{} (along with all other commands of the \texttt{numerica} package). +Use of \texttt{numerica} in \LyX{} exploits the mini-\LaTeX{} runs of +the instant preview facility of that program to give immediate feedback +on calculations without requiring the whole document to be compiled. +See Chapter~\ref{chap:LyX}. +\end{description} +More than one option can be used at a time by separating the options +with a comma; e.g. \texttt{\textbackslash usepackage{[}plus,tables{]}\{numerica\}}. +However, apart from Chapter~\ref{chap:LyX}, the present document +focuses on \texttt{numerica} when called with no options: \texttt{\textbackslash usepackage\{numerica\}}. + +\subsection{Simple examples of use} + +\label{subsec:introSimple-examples}A simple example of use is provided +by the document +\begin{verbatim} + \documentclass{minimal} + \usepackage{numerica} + \begin{document} + + \eval{$ mc^2 $}[m=70,c=299 792 458][8x] + + \end{document} + +\end{verbatim} +\noindent We have a formula between math delimiters: \verb`$ mc^2 $`. +We have wrapped a command \verb`\eval` around the lot, added an optional +argument in parentheses specifying numericaal values for the quantities +\texttt{m} and \texttt{c}, and concluded it all with a trailing optional +argument specifying that the result should be presented to $8$ places +of decimals and in scientific notation (the \verb`x`). Running \texttt{pdflatex} +on this document generates a pdf displaying +\begin{centred} +\eval{$ mc^2 $}[m=70,c=299 792 458][8x] +\end{centred} +\noindent where the formula ($mc^{2})$ is equated to the numerical +value resulting from substituting the given values of $m$ and $c$. +Those values are displayed in a list following the result. The calculation +is presented to $8$ decimal places in scientific notation. (According +to Einstein's famous equation $E=mc^{2}$ this is the enormous energy +content, in joules, of what was once considered an average adult Caucasian +male. Only a minute fraction is ever available.) + +A second example is provided by the formula in earlier remarks: +\begin{verbatim} + \documentclass{minimal} + \usepackage{numerica} + \begin{document} + + \eval{\[ \frac{\sin(3.5)}{2} + 2\cdot 10^{-3} \]} + + \end{document} + +\end{verbatim} +Running \texttt{pdflatex} on this document produces the result + +\eval{\[ \frac{\sin(3.5)}{2} + 2\cdot 10^{-3} \]} + +The \verb`\eval` command used in these examples is the main command +of the \texttt{numerica} package. It is discussed in full in the next +chapter, but first some preliminaries. + +\subsection{Display of the result} + +\label{subsec:introResultDisplay}In what follows I shall write things +like (but generally more complicated than) +\begin{centred} +\verb`$ \eval{ 1+1 } $` $\Longrightarrow \eval{ 1 + 1 } $ +\end{centred} +to mean: run \texttt{pdflatex} on a document containing \verb`\eval{1+1}` +in the document body to generate a pdf containing the calculated result +($2$ in this instance). In this case the \verb`\eval` command is +used \emph{within} a math environment (delimited by the dollar signs). +It is not limited to this behaviour. The command can also wrap \emph{around} +the math delimiters (as we saw in the previous examples): +\begin{centred} +\verb`\eval{$ 1+1 $}` $\Longrightarrow$ \eval{$ 1+1 $}. +\end{centred} +As you can see, the display that results is different. +\begin{itemize} +\item When the \verb`\eval` command is used\emph{ within} a math environment, +only the \emph{result,} followed possibly by the \emph{variable~=~value +list} (see §\ref{subsec:evalVv-list}) is displayed. +\end{itemize} +Environments may include the various AMS environments as well as the +standard \LaTeX{} inline ( \verb`$ $` ), \texttt{equation} ( \verb`\[ \]` +) and \texttt{eqnarray} environments. For an example of \verb`\eval` +within an \verb`align*` environment see §\ref{subsec:introExploring} +below. +\begin{itemize} +\item When the \verb`\eval` command is wrapped\emph{ around} a math environment, +the result is displayed in the form, \emph{formula = result} (followed +possibly by the \emph{variable~=~value list}) within that environment, +\begin{itemize} +\item If the formula is long or contains many variables then it may be desirable +to split the display over two lines; see §\ref{subsec:evalChanging-display-format} +and §\ref{subsec:settings New-line-display}, +\end{itemize} +\end{itemize} +the whole presented as an inline expression if \verb`$` delimiters +are used, or as a display-style expression otherwise. (See the $mc^{2}$ +example for an illustration.) + +It is not clear to me that wrapping \verb`\eval` \emph{around} the +AMS environments, except for \texttt{multline}, makes much sense, +although it can be done. Here is an example of \verb`\eval` wrapped +around a \texttt{multline{*}} environment (the phantom is there so +that the hanging $+$ sign spaces correctly),\medskip{} + +\begin{minipage}[t]{0.8\columnwidth}% +\begin{verbatim} +\eval{ \begin{multline*} + 1+2+3+4+5+6+7+8+9+10+\phantom{0}\\ + 11+12+13+14+15+16+17+18+19 + \end{multline*} } +\end{verbatim} +% +\end{minipage} + +\medskip{}$\Longrightarrow$ % +\begin{minipage}[t]{0.8\columnwidth}% +\vspace{-2ex}\eval{ \begin{multline*} + 1+2+3+4+5+6+7+8+9+10+\phantom{0}\\ 11+12+13+14+15+16+17+18+19 +\end{multline*} }% +\end{minipage} +\begin{itemize} +\item It is also possible to dispense with math delimiters entirely, neither +wrapped within nor wrapped around the \verb`\eval` command, but in +that case \texttt{numerica} acts as if \verb`\eval` had been used +within \verb`\[` and \verb`\]` and displays the result accordingly. +\end{itemize} + +\subsection{Exploring} + +\label{subsec:introExploring}When working on \texttt{numerica}'s +predecessor package, I constantly tested it against known results +to check for coding errors. One test was to ensure that +\[ +\left(1+\frac{1}{n}\right)^{n} +\] +did indeed converge to the number $e$ as $n$ increased.\texttt{ }Let's +do that here. Try first $n=10$: +\begin{center} +\verb`\eval{$ e-(1+1/n)^n $}[n=10][x]` $\Longrightarrow$ \eval{$ e-(1+1/n)^n $}[n=10][x]. +\par\end{center} + +\noindent (The default number of decimal places displayed is $6$.) +The difference between $e$ and $(1+1/n)^{n}$ is about an eighth +($0.125$) when $n=10$, which is encouraging but hardly decisive. +The obvious thing to do is increase the value of $n$. I'll use an +\verb`align*` environment to `prettify' the presentation of the +results: +\begin{verbatim} + \begin{align*} + e-(1+1/n)^{n} & =\eval{e-(1+1/n)^n}[n=1\times10^5][*x],\\ + e-(1+1/n)^{n} & =\eval{e-(1+1/n)^n}[n=1\times10^6][*x],\\ + e-(1+1/n)^{n} & =\eval{e-(1+1/n)^n}[n=1\times10^7][*x],\\ + e-(1+1/n)^{n} & =\eval{e-(1+1/n)^n}[n=1\times10^8][*x]. + \end{align*} +\end{verbatim} +(most of which was written using copy and paste) which produces + +\begin{align*} +e-(1+1/n)^{n} & =\eval{e-(1+1/n)^{n}}[n=1\times10^{5}][x],\\ +e-(1+1/n)^{n} & =\eval{e-(1+1/n)^{n}}[n=1\times10^{6}][*x],\\ +e-(1+1/n)^{n} & =\eval{e-(1+1/n)^{n}}[n=1\times10^{7}][x],\\ +e-(1+1/n)^{n} & =\eval{e-(1+1/n)^{n}}[n=1\times10^{8}][x]. +\end{align*} +Clearly $(1+1/n)^{n}$ converges to $e$, the difference between them +being of order $1/n$, but that is not what catches the eye. There +is an unanticipated regularity here. 1.35914? Double the number: \verb`$\eval{2\times 1.35914}[5]$`\texttt{ +}$\Longrightarrow\eval{2\times1.35914}[5]$ which is close enough +to $e$ to suggest a relationship, namely, +\[ +\lim_{n\to\infty}n\left(e-\left(1+\frac{1}{n}\right)^{n}\right)=\tfrac{1}{2}e. +\] + +This was new to me. Is it true? From the familiar expansion of the +logarithm + +\begin{align*} +\ln\left(1+\frac{1}{n}\right)^{n} & =n\ln\left(1+\frac{1}{n}\right)\\ + & =n\left(\frac{1}{n}-\frac{1}{2}\frac{1}{n^{2}}+\frac{1}{3}\frac{1}{n^{3}}-\ldots\right)\\ + & =1-\frac{1}{2n}\left(1-\frac{2}{3}\frac{1}{n}+\frac{2}{4}\frac{1}{n^{2}}-\right)\\ + & \equiv1-\frac{1}{2n}E_{n}, +\end{align*} +say. Since $E_{n}$ is an alternating series and the magnitudes of +the terms of the series tend to $0$ monotonically, $1>E_{n}>1-2/3n$. +From this and the inequalities $1/(1-x)>e^{x}>1+x$ when $x<1$ it +proved a straightforward matter to verify the proposed limit. + +\subsection{Reassurance} + +\label{subsec:introReassurance}In the course of some hobbyist investigations +in plane hyperbolic geometry I derived the formula +\[ +\Phi_{1}(m,n)=\cos\tfrac{m}{n}\pi-(1-4\sin^{2}\tfrac{m}{3n}\pi)\frac{\sin\tfrac{1}{n}\pi\sin\tfrac{m-1}{n}\pi}{2\sin^{2}\tfrac{m}{3n}\pi}, +\] +for $m=2,3,\ldots$ and integral $n\ge2m+1$. A key concern was: when +is $\Phi_{1}$ positive? After an embarrassingly laborious struggle, +I managed to work this expression into the form +\[ +\Phi_{2}(m,n)=\left(\frac{1-4\sin^{2}\tfrac{m}{3n}\pi}{2\sin^{2}\tfrac{m}{3n}\pi}\right)\sin\tfrac{2m-3}{3n}\pi\sin\tfrac{m-3}{3n}\pi, +\] +in which the conditions for positivity are clear: with $n\ge2m+1$, +so that $m\pi/3n<\pi/6$, the first factor is always positive, the +second is positive for $m\ge2$, and the third is positive for $m\ge4$. +All well and good, but given the struggle to derive $\Phi_{2}$, was +I confident that $\Phi_{1}$ and $\Phi_{2}$ really\emph{ }are equal? +It felt all too likely that I had made a mistake. + +The simplest way to check was to see if the two expressions gave the +same numericaal answers for a number of $m,\thinspace n$ values. +I wrote \verb`\eval{\[ \]}[m=2,n=5]` twice and between the delimiters +pasted the already composed expressions for $\Phi_{1}$ and $\Phi_{2}$, +namely: +\begin{verbatim} + \eval{\[ + \cos\tfrac{m}{n}\pi-(1-4\sin^{2}\tfrac{m}{3n}\pi) + \frac{\sin\tfrac{1}{n}\pi\sin\tfrac{m-1}{n}\pi} + {2\sin^{2}\tfrac{m}{3n}\pi} + \]}[m=2,n=5] + \eval{\[ + \left( + \frac{1-4\sin^{2}\tfrac{m}{3n}\pi} + {2\sin^{2}\tfrac{m}{3n}\pi} + \right) + \sin\tfrac{2m-3}{3n}\pi\sin\tfrac{m-3}{3n}\pi + \]}[m=2,n=5] +\end{verbatim} +I have added some formatting – indenting, line breaks – to make the +formulas more readable for the present document but otherwise left +them unaltered. The \verb`\eval` command can be used for even quite +complicated expressions without needing to tinker with their \LaTeX{} +form, but you may wish – as here – to adjust white space to clarify +the component parts of the formula. Running \texttt{pdflatex} on these +expressions, the results were + +\eval{\[ + \cos\tfrac{m}{n}\pi-(1-4\sin^{2}\tfrac{m}{3n}\pi) + \frac{\sin\tfrac{1}{n}\pi\sin\tfrac{m-1}{n}\pi} + {2\sin^{2}\tfrac{m}{3n}\pi} + \]}[m=2,n=5] + +\eval{\[ + \left( + \frac{1-4\sin^{2}\tfrac{m}{3n}\pi} + {2\sin^{2}\tfrac{m}{3n}\pi} + \right) + \sin\tfrac{2m-3}{3n}\pi\sin\tfrac{m-3}{3n}\pi + \]}[m=2,n=5] + +\noindent which was reassuring. Doing it again but with different +values of $m$ and $n$, again the results coincided: + +\eval{\[ + \cos\tfrac{m}{n}\pi-(1-4\sin^{2}\tfrac{m}{3n}\pi) + \frac{\sin\tfrac{1}{n}\pi\sin\tfrac{m-1}{n}\pi} + {2\sin^{2}\tfrac{m}{3n}\pi} + \]}[m=5,n=13] + +\eval{\[ + \left( + \frac{1-4\sin^{2}\tfrac{m}{3n}\pi} + {2\sin^{2}\tfrac{m}{3n}\pi} + \right) + \sin\tfrac{2m-3}{3n}\pi\sin\tfrac{m-3}{3n}\pi + \]}[m=5,n=13] + +\noindent Thus reassured that there was \emph{not }an error in my +laborious derivation of $\Phi_{2}$ from $\Phi_{1}$, it was not difficult +to work back from $\Phi_{2}$ to $\Phi_{1}$ then reverse the argument +to find a straightforward derivation. + +\chapter{\texttt{\textbackslash nmcEvaluate} (\texttt{\textbackslash eval)}} + +The main calculational command in \texttt{numerica} is \verb`\nmcEvaluate`. +Unlike some other commands which are loaded optionally, \verb`\nmcEvaluate` +is \emph{always} loaded, and therefore always available. Because \verb`\nmcEvaluate` +would be tiresome to write too frequently,\texttt{ }particularly for +back-of-envelope calculations, there is an equivalent short-name form, +\verb`\eval`, used almost exclusively in the following. But note: +wherever you see the command \verb`\eval`, you can substitute \verb`\nmcEvaluate` +and obtain the same result. + +\verb`\eval` (like other short-name forms of other commands in the +\texttt{numerica} suite) is defined using \verb`\ProvideDocumentCommand` +from the \texttt{xparse} package. Hence if \verb`\eval` has already +been defined in some other package already loaded, it will not be +redefined by \texttt{numerica}. It will retain its meaning in the +other package. Its consequent absence from \texttt{numerica} may be +an irritant, but only that; \verb`\nmcEvaluate` is defined using +\texttt{xparse}'s \verb`\DeclareDocumentCommand` which would override +any (freakishly unlikely) previous definition of \verb`\nmcEvaluate` +in another package and would therefore still be available. + +\section{Syntax of \texttt{\textbackslash nmcEvaluate (\textbackslash eval)}} + +There are five arguments to the \verb`\nmcEvaluate` (or \verb`\eval`) +command, of which only one, the third, is mandatory. All others are +optional. If all are deployed the command looks like +\begin{centred} +\noindent \verb`\eval*[settings]{expr.}[vv-list][num. format]` +\end{centred} +I discuss the various arguments in the referenced sections. +\begin{enumerate} +\item \verb`*` optional switch; if present ensures display of only the +numerical result (suppresses display of the formula and vv-list); +see §\ref{subsec:evalVvSuppresList} +\item \verb`[settings]` optional comma-separated list of \emph{key=value +}settings for this particular calculation; see §\ref{sec:settingsOption} +\item \verb`{expr.}` the only mandatory argument; the mathematical expression/formula +in \LaTeX{} form that is to be evaluated +\item \verb`[vv-list]` optional comma-separated list of \emph{variable=value +}items; see §\ref{subsec:evalVv-list} +\item \verb`[num. format]` optional format specification for presentation +of the numerical result (rounding, padding with zeros, scientific +notation, boolean output); see~§\ref{subsec:evalRoundingEtc} +\end{enumerate} +Note that arguments 4 and 5 are both square-bracket delimited optional +arguments. Should only one such argument be used, \texttt{numerica} +determines which is intended by looking for an equals sign within +the argument. Its presence indicates the argument is the vv-list; +its absence indicates the argument is the number format specification. + +The vv-list and number-format specification are \emph{trailing} optional +arguments. There is a possibility that the \verb`\eval` command could +be followed by a square-bracketed mathematical expression which \texttt{numerica} +might therefore confuse with one of its trailing arguments. Experience +using \texttt{numerica} suggests that this will be a (very) rare occurrence +and is easily prevented by inserting an empty brace pair (\verb`{}`) +before the offending square-bracketed expression. Allowing spaces +between the arguments enables complicated expressions and large vv-lists +to be formatted, in the interests of clarity, with new lines and white +space – without requiring the insertion of comment characters (\verb`%`). + +Recommended practice is to minimise the number of optional arguments +used in \LaTeX{} commands by consolidating such arguments into a single +\emph{key=value} list. Although \texttt{numerica} uses such an argument, +the vv-list does not fit naturally into that scheme. And practice +suggests that separating out the elements of the number format specification +(rounding value, padding with zeros, scientific notation, boolean +output) and placing them in a trailing argument feels natural for +the kind of back-of-envelope calculations envisaged for \texttt{numerica}. + +\section{The variable=value list} + +\label{subsec:evalVv-list}To evaluate algebraic, trigonometric and +other formulas that involve \emph{variables} we need to give those +variables values. This is done in the \emph{variable=value list} – +or \emph{vv-list} for short. This is the fourth argument of the \texttt{\textbackslash nmcEvaluate} +command and is a square-bracket delimited optional argument (optional +because an expression may depend only on constants and numbers). + +\noindent\begin{minipage}[t]{1\columnwidth}% +\begin{shaded}% +I was sorely tempted to use parentheses to delimit this argument, +since then both the placement and delimiters of the vv-list would +anticipate the way it is displayed in the evaluated result (see the +$mc^{2}$ example in §\ref{subsec:introSimple-examples} above). But +there is good reason not to. Parentheses will often occur in expressions +in the vv-list. With parentheses nested within parentheses it is all +too easy to get a pairing wrong, which would cause a \LaTeX{} error +and halt compilation. As it is, using the standard square bracket +delimiters, unbalanced parentheses cause a \texttt{numerica} error +(see §\ref{subsec:errorsMismatched-brackets}), which does not halt +compilation. (Of course unbalanced \emph{square} brackets now will +cause a \LaTeX{} error, but such brackets are used less often in mathematical +expressions and are rarely nested within other square-bracketed expressions.)\end{shaded}% +\end{minipage} + +\subsection{Variable names} + +\label{subsec:evalVariableNames}In mathematical practice, variable +names are generally single letters of the Roman or Greek alphabets, +sometimes also from other alphabets, in a variety of fonts, and often +with subscripts or primes or other decorations. In \texttt{numerica} +a variable name is \emph{what lies to the left of the equals sign +in an item} of the vv-list. Thus variables can be multi-token affairs: +$x',x'',x^{iv},x_{n},x'_{n},x''_{mn}$, $^{k}C_{n},var,\mathrm{var},Fred,\mathbf{Fred},\mathcal{FRED}\ldots$ +Although variable names start and end with non-space tokens, a variable +name may contain spaces – for instance \verb`x x` should not cause +a \verb`numerica` error, but such names are not part of mathematical +practice. Usually, for the kind of back-of-envelope calculations envisaged +for \verb`numerica`, and for ease of typing, most variables will +be single letters from the Roman or Greek alphabets. + +Because equals signs and commas give structure to the vv-list, it +should also be clear that a variable name should not contain a \emph{naked} +equals sign or a \emph{naked} comma. They can be incorporated in a +variable name but only when decently wrapped in braces, like \verb`R_{=}` +displaying as $R_{=}$ or \verb`X_{,i}` displaying as $X_{,i}$. + +Note that $x$ and $\mathrm{x}$ will be treated by \verb`numerica` +as \emph{different} variables since, in the underlying \LaTeX , one +is \texttt{x} and the other \verb`\mathrm{x}`. Even names that look +identical in the pdf may well be distinct in \LaTeX . This is true +particularly of superscripts and subscripts: \verb`x_0` and \verb`x_{0}` +appear identical in the pdf but in the underlying \LaTeX{} they are +distinct, and will be treated as distinct variables by \verb`numerica`. + +Although multi-token variables are perfectly acceptable, \emph{internally} +\verb`numerica` expects variables to be single tokens. Hence a necessary +initial step for the package is to convert all multi-token variable +names in the vv-list and the formula to single tokens. \verb`numerica` +does this by turning the multi-token variable names into control sequences +with names in the sequence \verb`\_nmca`, \verb`\_nmcb`, \verb`\_nmcc`, +etc., then searches through the vv-list and the formula for every +occurrence of the multi-token names and replaces them with the relevant +control sequences. It does this in order of decreasing size of name, +working from the names that contain most tokens down to names containing +only two tokens. + +The conversion process uses computer resources. Even if there are +no multi-token variables present, \verb`numerica` still needs to +check that this is so – unless the user alerts the program to the +fact. This can be done by making a brief entry \texttt{xx=0 }in the +settings option (the second optional argument of \verb`\nmcEvaluate`); +see §\ref{subsec:settingsMultitokSwitch}. If the user never (or hardly +ever) uses multi-token variables, then a more permanent solution is +to create a file \verb`numerica.cfg`\texttt{ }with the line \texttt{multitoken-variables += false}; see §\ref{sec:settingsDefaults} for this. + +\subsection{The vv-list and its use} + +A vv-list is a comma-separated list where each item is of the form +\emph{variable=value}. It might be something simple like +\begin{lyxcode} +{[}g=9.81,t=2{]} +\end{lyxcode} +or something more complicated like +\begin{lyxcode} +{[}V\_S=\textbackslash tfrac43\textbackslash pi~r\textasciicircum 3,V\_C=2\textbackslash pi~r\textasciicircum 2h,h=3/2,r=2{]}. +\end{lyxcode} +Spaces around the equals signs or the commas are stripped away during +processing so that +\begin{lyxcode} +{[}g=9.81,t=2{]}~\textrm{and}~{[}~g~=~9.81~,~t~=~2{]} +\end{lyxcode} +are the \emph{same} variable=value list. + +\subsubsection{Evaluation from right to left} + +In these examples, with variables depending on other variables, there +is an implication: that the list is evaluated \emph{from the right}. +Recall how a function of a function is evaluated, say\emph{ }$y=f(g(h(x)))$. +To evaluate $y$, first $x$ is assigned a value then $h(x)$ is calculated, +then $g(h(x))$ then $f(g(h(x)))=y$. We work from right to left, +from the innermost to the outermost element. Or consider an example +like calculating the area of a triangle by means of the formula +\[ +A=\sqrt{s(s-a)(s-b)(s-c)}. +\] +First we write the formula; then we state how $s$ depends on $a,b,c$, +namely $s=\frac{1}{2}(a+b+c)$, then we give values to $a,b,c$. In +\texttt{numerica} this is mirrored in the layout of the \verb`\eval` +command: +\begin{verbatim} + \eval{$ \sqrt{s(s-a)(s-b)(s-c)} $} + [s=\tfrac12(a+b+c),a=3,b=4,c=5] +\end{verbatim} +The formula in a sense is the leftmost extension of the vv-list. The +entire evaluation occurs from right to left. + +This means that the rightmost variable in the vv-list can depend only +on (mathematical) constants and numbers – although it may be a complicated +expression of those elements. Other variables in the vv-list can depend +on variables \emph{to their right} but not to their left. + +\subsubsection{Expressions in the variable=value list} + +Suppose our expression is $\tfrac{4}{3}\pi r^{3}$, the volume $V_{S}$ +of a sphere in terms of its radius $r$, and we want to calculate +the volume for different values of $r$ to get a sense of how rapidly +volume increases with radius. +\begin{centred} +\verb`$ V_S=\eval{ \tfrac43\pi r^3 }[r=1] $` $\Longrightarrow$ $ V_S=\eval{ \tfrac43\pi r^3 }[r=1] $. +\end{centred} +Having set up this calculation it is now an easy matter to change +the value of $r$ in the vv-list: +\begin{centred} +\verb`$ V_S=\eval{ \tfrac43\pi r^3 }[r=1.5] $` $\Longrightarrow$ +$ V_S= \eval{ \tfrac43\pi r^3 }[r=1.5] $. + +\verb`$ V_S=\eval{ \tfrac43\pi r^3 }[r=2] $` $ \Longrightarrow $ $V_S= \eval{ \tfrac43\pi r^3 }[r=2] $. +\end{centred} +To compute the volume $V_{C}=\pi r^{2}h$ of a cylinder, we have two +variables to assign values to: +\begin{centred} +\verb`$ V_C=\eval{ \pi r^2h }[h=4/3,r=1] $` $\Longrightarrow$ $ V_C=\eval{ \pi r^2h }[h=4/3,r=1] $. +\end{centred} +Although values in the vv-list are generally either numbers or simple +expressions (like \texttt{4/3}), that is not essential. A little more +complicated is +\begin{centred} +\verb`$ V_C=\eval{ hA_C }[A_C=\pi r^2,h=4/3,r=1] $` $\Longrightarrow$ +$ V_C=\eval{ hA_C }[A_C=\pi r^2,h=4/3,r=1] $. +\end{centred} +where calculation of the volume of the cylinder has been split into +two: first calculate the area $A_{C}$ of its circular base and then, +once that has been effected, calculate the volume. + +A second example is provided by Brahmagupta's formula for the area +of a triangle in terms of its semi-perimeter. In a triangle ABC, the +sides are $a=3$, $b=4$ and $c=5$. (Of course we know this is a +right-angled triangle with area $\tfrac{1}{2}ab=6$.) The semi-perimeter +$s=\tfrac{1}{2}(a+b+c)$ and the area of ABC is \medskip{} +\begin{verbatim} + \eval{$ \sqrt{s(s-a)(s-b)(s-c) $} + [s=\tfrac12(a+b+c),a=3,b=4,c=5] +\end{verbatim} +$\Longrightarrow$ \eval{$ \sqrt{s(s-a)(s-b)(s-c)} $} + [s=\tfrac12(a+b+c),a=3,b=4,c=5]. + +\subsubsection{Constants} + +There are five constants built-in to \texttt{numerica}: \verb`\pi`, +the ratio of circumference to diameter of a circle, \verb`e`, the +base of natural logarithms, \verb`\gamma`, the limit of $\left(\sum_{1}^{N}1/n\right)-\ln N$ +as $N\to\infty$, \verb`\phi`, the golden ratio, equal to $\tfrac{1}{2}(1+\surd5)$, +and the utilitarian constant \verb`\deg`, the number of radians in +a degree. +\begin{centred} +\verb`\eval{$ \pi $}` $\Longrightarrow$ \eval{$ \pi $}, + +\verb`\eval{$ e $}` $\Longrightarrow$ \eval{$ e $}, + +\verb`\eval{$ \gamma $}` $\Longrightarrow$ \eval{$ \gamma $}, + +\verb`\eval{$ \phi $}` $\Longrightarrow$ \eval{$ \phi $}, + +\verb`\eval{$ \deg $}` $\Longrightarrow$ \eval{$ \deg $}, +\end{centred} +so that \verb`\eval{$ 180\deg $}` $\Longrightarrow$ \eval{$ 180\deg $} +(as it should). + +Let's combine two of these in a formula: +\begin{centred} +\verb`\eval{$ e^\pi-\pi^e $}` $\Longrightarrow$ \eval{$ e^\pi-\pi^e $}, +\end{centred} +which is close-ish to $\tfrac{1}{4}e$: \verb`\eval{$ \tfrac14e $}` +$\Longrightarrow$ \eval{$ \tfrac14e $}. + +\subsubsection{Use of \texttt{\textbackslash pi},\texttt{ e},\texttt{ \textbackslash gamma},\texttt{ +\textbackslash phi} as variables} + +In some contexts it may feel natural to use any or all of \verb`\pi`, +\verb`e`, \verb`\gamma` and \verb`\phi` as variables by assigning +values to them in the vv-list. \texttt{numerica} does not object. +The values assigned in this way override the constants' values. For +example, if the triangle we labelled ABC previously was instead labelled +CDE then it has sides $c=3,d=4$ and (note!) $e=5$. It's area therefore +is\medskip{} +\begin{verbatim} + \eval{$ \sqrt{s(s-c)(s-d)(s-e)} $} + [s=\tfrac12(c+d+e),c=3,d=4,e=5] +\end{verbatim} +$\Longrightarrow$ + +\eval{$ \sqrt{s(s-c)(s-d)(s-e)} $} + [s=\tfrac12(c+d+e),c=3,d=4,e=5].\medskip{} + +\noindent Since this is the correct area we see that \texttt{e} has +been treated as a variable with the assigned value $5$, not as the +constant. But if \texttt{e} (or \verb`\pi` or \verb`\gamma` or \verb`\phi`) +is not assigned a value in the vv-list then it has, by default, the +value of the constant. + +In the case of \texttt{e}, if you wish to use it as a variable, the +constant is always available as \verb`\exp(1)`. There is no similar +alternative available for \verb`\pi`, \verb`\gamma` or \verb`\phi` +although you can always do something like \verb`[\pi=<new value>,\pi_0=\pi]` +in the vv-list, so that \verb`\pi_0` now has the constant's value. + +\subsection{Display of the vv-list} + +By default, the vv-list is displayed with (in fact following) the +numerical result. That and the format of the display can both be changed. + +\subsubsection{Star option: suppressing display of the vv-list} + +\label{subsec:evalVvSuppresList}If display of the vv-list is not +wanted at all, only the numerical result, it suffices to attach an +asterisk (star) to the \texttt{\textbackslash eval} command: +\begin{centred} +\verb`$ V_C=\eval*{ hA_C }[A_C=\pi r^2,h=4/3,r=1] $` $\Longrightarrow$ +$ V_C=\eval*{ hA_C }[A_C=\pi r^2,h=4/3,r=1] $, +\end{centred} +or simply the naked result: +\begin{centred} +\verb`\eval*{$ hA_C $}[A_C=\pi r^2,h=4/3,r=1]` $\Longrightarrow$ +\eval*{$ hA_C $}[A_C=\pi r^2,h=4/3,r=1]. +\end{centred} +In the latter case, note that a negative result will display with +a hyphen for the minus sign unless you, the user, explicitly write +math delimiters around the \verb`\eval*` command: +\begin{centred} +\verb`\eval*{$ y $}[y=ax+b,x=2,a=-2,b=2]` $\Longrightarrow$ \eval*{$ y $}[y=ax+b,x=2,a=-2,b=2] +\end{centred} +The \verb`$` signs that \verb`\eval*` wraps around are ignored. +The star option delivers a number, pure and simple, with no accompaniments. + +\subsubsection{Suppressing display of items} + +\label{subsec:evalVvSuppressVars}You may wish to retain some variables +in the vv-list display, but not all. For those variables you wish +omitted from the display, wrap each variable (but not the equals sign +or value) in braces. When calculating the volume of a cylinder in +the previous examples, the base area $A_{C}$ has a different status +from the `fundamental' variables $r$ and $h$. It is an intermediate +value, one that we pass through on the way to the final result. To +suppress it from display enclose the variable in braces: +\begin{centred} +\verb`$ V_C=\eval{ hA_C }[{A_C}=\pi r^2,h=4/3,r=1] $` $\Longrightarrow$ +$ V_C=\eval{ hA_C }[{A_C}=\pi r^2,h=4/3,r=1] $. +\end{centred} +As you can see, $A_{C}$ no longer appears in the displayed vv-list. +Of course the name and its value are still recorded `behind the scenes' +and can still be used in calculations. + +\subsubsection{Changing the display format} + +\label{subsec:evalChanging-display-format}In two examples above, +we have calculated the area of a triangle using Brahmagupta's formula. +Display of the result is crowded. Two remedies have just been suggested, +but a third one and preferable in this case would be to force display +of the vv-list and result to a new line. This can be done through +the settings option to the \verb`\eval` command, discussed in §\ref{subsec:settings New-line-display}. +However, if \verb`\eval` is wrapped around an \emph{appropriate} +environment (like \verb`multline`, but not \verb`equation`) it can +also be done simply by including \texttt{\textbackslash\textbackslash} +at the end of the formula. + +In the following example I use Brahmagupta's formula for calculating +the area of a cyclic quadrilateral (of which his formula for a triangle +is a special case). The cyclic quadrilateral in the example is formed +by a 45-45-90 triangle of hypotenuse 2 joined along the hypotenuse +to a 30-60-90 triangle. The sides are therefore $\surd2,\surd2,\surd3,1$. +Adding the areas of the two triangles, the area of the quadrilateral +is $A=1+\tfrac{1}{2}\surd3$, or in decimal form, \verb`$\eval{1+\tfrac12\surd3}$` +$\Longrightarrow$ $\eval{1+\tfrac12\surd3}$. Let's check with Brahmagupta's +formula: +\begin{verbatim} + \eval{ + \begin{multline*} + \sqrt{(s-a)(s-b)(s-c)(s-d)}\\ + \end{multline*} + }[s=\tfrac12(a+b+c+d), + a=\surd2,b=\surd2,c=\surd3,d=1] +\end{verbatim} +$\Longrightarrow$ \eval{ + \begin{multline*} + \sqrt{(s-a)(s-b)(s-c)(s-d)}\\ + \end{multline*} + }[s=\tfrac12(a+b+c+d), + a=\surd2,b=\surd2,c=\surd3,d=1] + +\section{Formatting the numerical result} + +\label{subsec:evalRoundingEtc} A result of a calculation is displayed, +by default, to $6$ decimal places. All our results so far have been +rounded to this figure, although not all digits are displayed, for +instance if the sixth one is $0$, or the result is an integer. Like +other elements of the display, both rounding value and the (dis)appearance +of trailing zeros can be customized, in this case by means of an optional +argument following the vv-list (or the formula if there is no vv-list). +This optional argument may contain up to four juxtaposed items from +seven possibilities: +\begin{itemize} +\item a question mark ?, which gives boolean output, or +\item an integer, the \emph{rounding value}, positive, negative or zero, +specifying how many decimal places to display the result to, or +\item an asterisk {*}, which pads the result with zeros should it not have +as many decimal places as the rounding value specifies, or +\item the character \texttt{x} (lower case!) which presents the result in +`proper' scientific notation (a form like $1.234\times10^{5}$ for +123450), or +\item the character \texttt{t} (lower case!) which presents the result in +a bastardized form of scientific notation useful in tables (a form +like $(5)1.234$ for 123450), or +\item a character other than \texttt{?}, \texttt{{*}}, \texttt{x}, \texttt{t} +or a digit, usually (but not necessarily) one of the letters\texttt{ +e d} \texttt{E D}, which presents the result in scientific notation +using that character as the exponent mark (a form like $1.234\text{e}5$ +for $123450$), or +\item a prime +\begin{itemize} +\item attached to the character specifying scientific notation, which extends +that notation to numbers in the interval \texttt{{[}1,10)}, or +\item attached to a question mark, which changes the format of boolean output. +\end{itemize} +\end{itemize} +If you use \texttt{?} in the same specification as some other text +character, the \texttt{?} prevails; if you use \texttt{x} in the same +specification as some other text character except for \texttt{?}, +the \texttt{x} prevails; if you use \texttt{t} in the same specification +as some other text character except for \texttt{?} or \texttt{x}, +the \texttt{t} prevails. + +\subsection{Rounding value } + +\label{subsec:evalRounding-value}The rounding value specifies the +number of decimal places displayed: +\begin{centred} +\verb`$ \eval{ 1/3 }[4] $` $\Longrightarrow$ $ \eval{ 1/3 }[4] $ +\end{centred} +The default rounding value is $6$: +\begin{centred} +\verb`$ \eval{ 35/3 } $` $\Longrightarrow$ $ \eval{ 35/3 } $ +\end{centred} +Following the default behaviour in \texttt{l3fp}, `ties' are rounded +to the nearest \emph{even} digit. Thus a number ending $55$ has a +`choice' of rounding to $5$ or $6$ and rounds up to the even digit +$6$, and a number ending $65$ with a `choice' of rounding to $6$ +or $7$ rounds down to the even digit $6$: +\begin{centred} +\verb`$ \eval{ 0.1234555 } $` $\Longrightarrow\eval{0.1234555}$ + +\verb`$ \eval{ 0.1234565 } $` $\Longrightarrow\eval{0.1234565}$ +\end{centred} +The calculational engine which \texttt{numerica} uses, \texttt{l3fp}, +works to 16 significant figures and never displays more than that +number (and often less). +\begin{itemize} +\item In the first of the following although I have specified a rounding +value of $19$ only $16$ decimal places are displayed, with the final +digit rounded up to $7$; +\item in the second I have added $10$ zeros after the decimal point, meaning +that all $19$ decimal places specified by the rounding value can +be displayed since the 10 initial zeros do not contribute to the significant +figures; +\item in the third I have changed the figure \emph{before} the decimal point +to $1$ so that the $10$ added zeros are now included among the significant +figures; +\item and in the fourth, I have added $9$ digits before the decimal point: +\end{itemize} +\begin{centred} +\verb`$ \eval{ 0.1234567890123456789 }[19] $` $\Longrightarrow$ +$\eval{ 0.1234567890123456789 }[19]$ + +\verb`$ \eval{ 0.00000000001234567890123456789 }[19] $` $\Longrightarrow$ +$\eval{ 0.00000000001234567890123456789 }[19]$ + +\verb`$ \eval{ 1.00000000001234567890123456789 }[19] $` $\Longrightarrow$ +$\eval{ 1.00000000001234567890123456789 }[19]$ + +\verb`$ \eval{ 987654321.1234567890123456789 }[19] $` $\Longrightarrow$ +$\eval{ 987654321.1234567890123456789 }[19]$ +\end{centred} +In all cases, no more than $16$ \emph{significant} figures are displayed, +although the number of decimal places displayed may exceed $16$ as +in the second example. + +It is possible to use \emph{negative} rounding values. Such a value +zeroes the specified number of digits \emph{before} the decimal point. +\begin{centred} +\verb`$ \eval{ 987654321.123456789 }[-4] $` $\Longrightarrow$ $\eval{ 987654321.123456789 }[-4]$ +\end{centred} +A rounding value of $0$ rounds to the nearest integer: +\begin{centred} +\verb`$ \eval{ 987654321.123456789 }[0] $` $\Longrightarrow$ $\eval{ 987654321.123456789 }[0]$ +\end{centred} +If you wish to change the \emph{default} rounding value from $6$ +to some other value, this can be done by creating or editing a file +\texttt{numerica.cfg} in a text editor; see §\ref{sec:settingsDefaults}. + +\subsection{Padding with zeros } + +\label{subsec:evalPadding-with-zeros}A result may contain fewer decimal +places than the rounding value specifies, the trailing zeros being +suppressed by default (this is how \texttt{l3fp} does it). Sometimes, +perhaps for reasons of presentation like aligning columns of figures, +it may be desirable to pad results with zeros. This is achieved by +inserting an asterisk, {*}, into the final optional argument of the +\verb`\eval` command: +\begin{centred} +\verb`$ \eval{ 1/4 }[4] $` $\Longrightarrow$ $ \eval{ 1/4 }[4] $, + +\verb`$ \eval{ 1/4 }[4*] $` $\Longrightarrow$ $ \eval{ 1/4 }[4*] $. +\end{centred} + +\subsection{Scientific notation } + +\label{subsec:evalScientificNotation} The \texttt{l3fp} package can +output numbers in scientific notation. For example, $1234$ is rendered +as $\eval{1234}[e]$, denoting $1.234\times10^{3}$ , and $0.008$ +as $\eval{0.008}[e]$, denoting $8\times10^{-3}$. The `e' here, +the \emph{exponent mark}, separates the \emph{significand} ($1.234$) +from the \emph{exponent} ($3$). To switch on output in scientific +notation in \texttt{numerica} enter \texttt{e} in the trailing optional +argument: +\begin{centred} +\verb`$ \eval{ 123456789 }[e] $` $\Longrightarrow$ $ \eval{ 123456789 }[e] $. +\end{centred} +The default rounding value $6$ is in play here. In \texttt{numerica}, +when scientific notation is selected rounding takes a different meaning: +it is the \emph{significand }which is rounded (not the number as a +whole). One digit precedes the decimal point, at most $15$ follow +it. + +Negative rounding values are pointless for scientific notation. A +zero might on occasion be relevant: +\begin{centred} +\verb`$ \eval{ 987654321 }[0e] $` $\Longrightarrow$ $ \eval{ 987654321 }[0e] $. +\end{centred} +Sometimes letters other than `e' are used to indicate scientific +notation, like `E' or `d' or `D'. With a few exceptions, \texttt{numerica} +allows any letter or text character to be used as the exponent marker: +\begin{centred} +\verb`\eval{$ 1/23456789 $}[4d]`\texttt{ $\Longrightarrow$} \eval{$ 1/23456789 $}[4d]. +\end{centred} +But when \texttt{x} is inserted in the trailing optional argument, +the output is in the form $d_{0}.d_{1}\ldots d_{m}\times10^{n}$ (except +when $n=0$), where each $d_{i}$ denotes a digit. +\begin{centred} +\verb`\eval{$ 1/23456789 $}[4x]`\texttt{ $\Longrightarrow$ }\eval{$ 1/23456789 $}[4x] . +\end{centred} +The requirements of tables leads to another form of scientific notation. +Placing \texttt{t} in the trailing argument turns on this table-ready +form of notation: +\begin{centred} +\verb`\eval{$ 1/23456789 $}[4t]`\texttt{ $\Longrightarrow$ }\eval{$ 1/23456789 $}[4t]. +\end{centred} +This is discussed more fully in the associated document \texttt{numerica-tables.pdf}. + +In the next example three options are used in the trailing argument. +The order in which the items are entered does not matter: +\begin{centred} +\verb`\eval{$ 1/125 $}[*e4]` $\Longrightarrow$ \eval{$ 1/125 $}[*e4]. +\end{centred} +Finally, to illustrate that `any' text character\footnote{Be sensible! An equals sign for instance might confuse \texttt{numerica} +into thinking the number-format option is the vv-list, and will certainly +confuse the reader.} save for \texttt{x} or \texttt{t} can be used to distinguish the +exponent, I use an @ character: +\begin{centred} +\verb`\eval{$ 1/123 $}[@4]` $\Longrightarrow$ \eval{$ 1/123 $}[@4]. +\end{centred} + +\subsubsection{Numbers in \texttt{{[}1,10)}} + +Usually when scientific notation is being used, numbers with magnitude +in the interval $[1,10)$ are rendered in their normal decimal form, +$3.14159$ and the like. Occasionally it may be desired to present +numbers in this range in scientific notation (this can be the case +in tables where the alignment of a column of figures might be affected). +\texttt{numerica} offers a means of extending scientific notation +to numbers in this range by adding a prime to the letter chosen as +the exponent mark in the trailing optional argument. +\begin{centred} +\verb`\eval{$ \pi $}[4t']` $\Longrightarrow$ \eval{$ \pi $}[4t'] +\end{centred} + +\subsubsection{\textbackslash eval{*} and scientific notation} + +Scientific notation can be used for the numerical result output by +\verb`\eval*`: +\begin{centred} +\verb`\eval*{$ \pi $}[e']` $\Longrightarrow$ \eval*{$ \pi $}[e'] +\end{centred} +There is one catch: if you substitute \texttt{x} for \texttt{e} here, +\LaTeX{} will complain about a missing \verb`$`. An \texttt{x} in +the number-format option produces a \verb`\times` in the output which +requires a math environment. It is up to you, as the user, to provide +the necessary delimiters outside the \verb`\eval*` command. (This +applies even when \verb`\eval*` wraps around math delimiters.) + +(Because of the way \texttt{numerica} parses the number-format option, +entering a prime with neither exponent character nor question mark +specified will result in scientific output using \texttt{e} as the +exponent mark. The last example could have been written \verb`\eval*{$ \pi $}[']`.) + +\subsection{Boolean output} + +\label{subsec:evalBoolean-output}\texttt{l3fp} can evaluate comparisons, +outputting $0$ if the comparison is false, $1$ if it is true. By +entering a question mark, \texttt{?}, in the trailing optional argument, +you can force \texttt{numerica} to do the same depending as the result +of a calculation is zero or not. The expression being evaluated does +not need to be a comparison, \verb`$ \eval{\pi}[?] $` $\Longrightarrow$ $ \eval{\pi}[?]$, +but comparisons are what this is designed for. + +Possible comparison relations are \verb`=`, \verb`<`, \verb`>`, +\verb`\ne`, \verb`\neq`, \verb`\ge`, \verb`\geq`, \verb`\le`, +\verb`\leq`. Although programming languages use combinations like +\verb`<=` or \verb`>=`, \texttt{numerica} does \emph{not} accept +these (they are not part of standard \emph{mathematical} usage) and +will generate an error. An example where the relation is equality +exhibits a numerological curiosity:\footnote{The \texttt{{[}p=.{]}} of this and the next example ensures a full +stop appears in the correct place; see §\ref{subsec:settingsPunctuation}.} +\begin{centred} +\verb`\eval[p=.]{\[ \frac1{0.0123456789}=81 \]}[5?]` $\Longrightarrow$ +\eval[p=.]{\[ \frac1{0.0123456789}=81 \]}[5?] +\end{centred} +Notice the $5$ alongside the question mark in the trailing argument. +That is critical. Change the $5$ to a $6$ (or omit it since the +default rounding value is $6$) and the outcome is different: +\begin{centred} +\verb`\eval[p=.]{\[ \frac1{0.0123456789}=81 \]}[6?]` $\Longrightarrow$ +\eval[p=.]{\[ \frac1{0.0123456789}=81 \]}[6?] +\end{centred} +Now the relation is false. Evaluating the fraction to more than $6$ +places, say to $9$, we can see what is going on: +\begin{centred} +\verb`\eval{$ 1/0.0123456789 $}[9]` $\Longrightarrow$ \eval{$ 1/0.0123456789 $}[9]. +\end{centred} + +\subsubsection{Outputting \texttt{T} or \texttt{F}} + +To my eye, outputting $0$ or $1$ in response to a `question' like +$1/0.0123456789=81$ is confusing. It is easy to change the boolean +output from $0,1$ to a more appropriate $F,T$, or \texttt{$\texttt{F,\texttt{T}}$} +by adding a prime or two primes respectively to the question mark +in the number-format option. +\begin{centred} +\verb`\eval[p=.]{\[ \frac1{0.0123456789}=81 \]}[6?'']` $\Longrightarrow$ +\eval[p=.]{\[ \frac1{0.0123456789}=81 \]}[6?''] +\end{centred} +The default boolean output format is chosen to be $0,1$ in case an +\verb`\eval*` command is used within another \verb`\eval` command +(`nesting'– see Chapter~\ref{chap:Nesting}~). The inner command +needs to output a \emph{numerical} answer. + +\subsubsection{Rounding error tolerance} + +\label{subsec:evalToleranceRounding}If at least one of the terms +in a comparison is the result of a calculation, then it's value is +likely to contain rounding errors. What level of rounding error can +we tolerate before such errors interfere with the comparison being +made? \texttt{l3fp} tolerates none. It decides the truth or falsity +of a comparison to all $16$ significant figures: 1.000 0000 0000 +0000 and 1.000 0000 0000 0001 are \emph{not }equal in \texttt{l3fp}. +But for most purposes this will be far too severe a criterion. + +Suppose our comparison relation is $\varrho$, denoting one of =, +<, >, \verb`\le`, etc. If $X\rel Y$ then $X-Y\rel Y-Y$, i.e. $X-Y\rel0$. +This is what \texttt{numerica} does. It takes the right-hand side +of the relation from the left-hand side and then compares the \emph{rounded} +difference under $\varrho$ to $0$. The rounding value used is the +number specified with the question mark in the trailing argument of +the \verb`\eval` command or, if no number is present, the default +rounding value (`out of the box' this is $6$). Thus, in a recent +example, $1/0.0123456789-81$ when rounded to $5$ decimal places +is \@.$0.00000$, indistinguishable from zero at this rounding value; +hence the equality $1/0.0123456789=81$ is true. But when rounded +to $6$ places it is $0.000001$ which \emph{is} distinguishable from +zero and so the equality is false. Truth or falsity depends on the +rounding value. + +When dealing with numbers generated purely mathematically, rounding +values of $5$ or $6$ are likely to be too small. More useful would +be rounding values closer to \texttt{l3fp}'s $16$ – perhaps $14$? +– depending on how severe the calculations are that generate the numbers. +However if the numbers we are dealing with come from outside mathematics, +from practical experiments perhaps, then even a rounding value of +$5$ or $6$ may be too large. + +\subsubsection{Rationale} + +Mathematically, the claim that $X=Y$ at a rounding value $n$ is +the claim that +\[ +\abs{X-Y}\le5\times10^{-(n+1)}. +\] +since this rounds \emph{down} to zero at $n$ places of decimals. +This gives a more accurate test of equality than doing things in the +opposite order – rounding each number first and then taking the difference. +One might, for instance, have numbers like $X=0.12345$, $Y=0.12335$. +Rounding to $n=4$ places, both round to $0.1234$ and yet the difference +between them is $0.0001$ – they are distinguishable numbers to $4$ +places of decimals. This is why \texttt{numerica} forms the difference +\emph{before }doing the rounding. + +\subsubsection{And, Or, Not} + +For logical And \LaTeX{} provides the symbols \verb`\wedge` and \verb`\land`, +both displaying as $\land$, but \texttt{numerica} adds thin spaces +( \verb`\,` ) around the symbol for \verb`\land` (copying the package +\texttt{gn-logic14.sty}). For logical Or \LaTeX{} provides the symbols +\verb`\vee` and \verb`\lor`, both displaying as $\lor$, but again +\texttt{numerica} adds thin spaces around the symbol for \verb`\lor`. +\begin{centred} +\verb`\eval{$ 1<2 \wedge 2<3 $}[?'']` $\Longrightarrow$ \eval{$ 1<2 \wedge 2<3 $}[?''], + +\verb`\eval{$ 1<2 \land 2<3 $}[?'']` $\Longrightarrow$ \eval{$ 1<2 \land 2<3 $}[?'']. +\end{centred} +To my eye the second of these with its smidgen more space around the +wedge symbol displays the meaning of the overall expression better +than the first. Both And and Or have equal precedence; in cases of +ambiguity the user needs to parenthesize as necessary to clarify what +is intended. + +\LaTeX{} provides two commands for logical Not, \verb`\neg` and \verb`\lnot`, +both displaying as $\lnot$ . Not binds tightly to its argument: +\begin{centred} +\verb`\eval{$ \lnot A \land B $}[A=0,B=0]` $\Longrightarrow$ \eval{$ \lnot A \land B $}[A=0,B=0]. +\end{centred} +Here \verb`\lnot` acts only on the $A$; if it had acted on $A\land B$ +as a whole the result would have been $1$. + +For a little flourish, I evaluate a more complicated logical statement:\footnote{Quoting from an article in \emph{Quanta Magazine} (August 2020) by +Kevin Hartnett: `Let’s say you and two friends are planning a party. +The three of you are trying to put together the guest list, but you +have somewhat competing interests. Maybe you want to either invite +Avery or exclude Kemba. One of your co-planners wants to invite Kemba +or Brad or both of them. Your other co-planner, with an ax to grind, +wants to leave off Avery or Brad or both of them. Given these constraints, +you could ask: Is there a guest list that satisfies all three party +planners?' I have written $C$ for Kemba, $A$ and $B$ for Avery +and Brad.} +\begin{verbatim} + \eval{$(A\lor\lnot C)\land(C\lor B)\land + (\lnot A\lor\lnot B)$}[A=1,B=0,C=1][?''] +\end{verbatim} +$\Longrightarrow$ \eval{$(A\lor\lnot C)\land(C\lor B)\land + (\lnot A\lor\lnot B)$}[A=1,B=0,C=1][?''] + +\subsubsection{Chains of comparisons} + +\texttt{numerica} can handle chains of comparisons like $1<2<1+2<5-1$. +`Behind the scenes' it inserts logical And-s into the chain, $1<2\land2<1+2\land1+2<5-1$, +and evaluates the modified expression: +\begin{centred} +\verb`\eval{$ 1<2<1+2<5-1 $}[?'']` $\Longrightarrow$ \eval{$ 1<2<1+2<5-1 $}[?'']. +\end{centred} + +\subsubsection{\texttt{amssymb} comparison symbols} + +\label{subsec:evalAmssymb-comparisons}\texttt{numerica} accepts some +alternative symbols for the basic comparison relations from the \texttt{amssymb} +package provided that package is loaded, i.e. the preamble of your +document includes the statement +\begin{lyxcode} +\textbackslash usepackage\{amssymb\} +\end{lyxcode} +The variants from this package are: \verb`\leqq` ( $\leqq$ ), \verb`\leqslant` +( $\leqslant$ ), \verb`\geqq` (~$\geqq$~), and \verb`\geqslant` +( $\geqslant$ ).\footnote{No, that is not \texttt{eggplant}.} There +are also negations: \verb`\nless` ( $\nless$ ), \verb`\nleq` (~$\nleq$~), +\verb`\nleqq` ( $\nleqq$ ), \verb`\nleqslant` ( $\nleqslant$ ), +\verb`\ngtr` ( $\ngtr$ ), \verb`\ngeq` ( $\ngeq$ ), \verb`\ngeqq` +( $\ngeqq$ ), \verb`\ngeqslant` ( $\ngeqslant$ ). + +\section{Calculational details} + +\subsection{Arithmetic} + +\label{subsec:evalArithmetic}Addition, subtraction, multiplication, +division, square roots, \emph{$n$}-th roots, and exponentiating (raising +to a power) are all available. + +Multiplication can be rendered explicitly with an asterisk, +\begin{centred} +\verb`\eval{$ 9*9 $}` $\Longrightarrow$ \eval{$ 9*9 $}, +\end{centred} +but that's ugly. More elegant is to use \verb`\times`: +\begin{centred} +\verb`\eval{$ 9\times9 $}` $\Longrightarrow$ \eval{$ 9\times9 $}. +\end{centred} +\verb`\cdot` is also available and in many cases juxtaposition alone +suffices: +\begin{centred} +\verb`\eval{$ \surd2\surd2 $}` $\Longrightarrow$ \eval{$ \surd2\surd2 $}, + +\verb`\eval{$ ab $}[a=123,b=1/123]` $\Longrightarrow$ \eval{$ ab $}[a=123,b=1/123]. +\end{centred} +Division can be rendered in multiple ways too: +\begin{centred} +\verb`\eval{$ 42/6 $}` $\Longrightarrow$ \eval{$ 42/6 $}, + +\verb`\eval{$ 42\div6 $}` $\Longrightarrow$ \eval{$ 42\div6 $}, +\end{centred} +or by using \verb`\frac` or \verb`\tfrac` or \verb`\dfrac` as in +\begin{centred} +\verb`\eval{$ \frac{42}6 $}` $\Longrightarrow$ \eval{$ \frac{42}6 $}. +\end{centred} +But note that since juxtaposition means multiplication, it is also +true that $42\tfrac{1}{6}$\texttt{ }evaluates to $7$ inside an \verb`\eval` +command rather than denoting `forty two and a sixth'. Hence if you +want to use `two and a half' and similar values in \texttt{numerica}, +they need to be entered as improper fractions like $\tfrac{5}{2}$ +or in decimal form, $2.5$ (as one does automatically in mathematical +expressions anyway because of the ambiguity in a form like $2\tfrac{1}{2}$). + +\subsubsection{Square roots and $n$-th roots} + +\label{subsec:evalSquareRootsEtc}Let us check that 3, 4, 5 and 5, +12, 13 really are Pythagorean triples (I use \verb`\sqrt` in the +first, \verb`\surd` in the second): +\begin{centred} +\verb`\eval{$ \sqrt{3^2+4^2} $}` $\Longrightarrow$ \eval{$\sqrt{3^{2}+4^{2}}$}, + +\verb`\eval{$ \surd(5^2+12^2) $}` $\Longrightarrow$ \eval{$ \surd(5^2+12^2) $}. +\end{centred} +The \verb`\sqrt` command has an optional argument which can be used +for extracting $n$-th roots of a number. This notation is generally +used when $n$ is a small positive integer like $3$ or $4$. This +practice is followed in \texttt{numerica}: $n$ must be a (not necessarily +small) \emph{positive integer}: +\begin{centred} +\verb`\eval{$ \sqrt[4]{81} $}` $\Longrightarrow$ \eval{$ \sqrt[4]{81} $}, + +\verb`\eval{$ \sqrt[n]{125} $}[n=\floor{\pi}]` $\Longrightarrow$ +\eval{$ \sqrt[n]{125} $}[n=\floor{\pi}]. +\end{centred} +If $n$ should not be a positive integer, an error message is generated; +see §\ref{sec:evalErrors}. + +For display-style expressions, the \verb`\sqrt` command grows to +accommodate the extra vertical height; the surd doesn't. Here is an +example which anticipates a number of matters not discussed yet. It +shows \verb`\eval` wrapping around a square root containing various +formatting commands (negative spaces, \verb`\left` and \verb`\right` +nested within \verb`\bigg` commands), all digested without complaint +(see §\ref{subsec:evalFormatting-commands}; and see §\ref{subsec:settingsPunctuation} +for the \verb`[p=.]`): \medskip{} +\begin{verbatim} + \eval[p=.] + {\[ + \sqrt[3] + {\!\biggl(\!\left.\frac AD\right/\!\frac BC\biggr)} + \]}[A=729,B=81,C=9,D=3] +\end{verbatim} +$\Longrightarrow$\eval[p=.] + {\[ + \sqrt[3] + {\!\biggl(\!\left.\frac AD\right/\!\frac BC\biggr)} + \]}[A=729,B=81,C=9,D=3] + +As implemented in \texttt{numerica}, $n$-th roots found using \verb`\sqrt[n]` +are \verb`n=<integer>`\emph{ }roots. This raises an interesting question: +if the `$n$' of an $n$-th root is the result of a calculation, +what happens with rounding errors? The calculation may not produce +an \emph{exact} integer. (This problem also arises with factorials; +see §\ref{subsec:evalFactorialsBinom}.) The solution employed in +\texttt{numerica} is to make what is considered an integer depend +on a rounding value. Most calculations will produce rounding errors +in distant decimal places. For `int-ifying' calculations, \texttt{numerica} +uses a rounding value of $14$: a calculation produces an integer +if, when rounded to $14$ figures, the result is an integer. Since +\texttt{l3fp} works to $16$ significant figures, a rounding value +of $14$ allows ample `elbowroom' for rounding errors to be accommodated +when judging what is an integer and what is not. As a practical matter +problems should not arise. + +\subsubsection{\emph{n}-th roots of negative numbers} + +Odd (in the sense of `not even') integral roots of \emph{negative} +numbers are available with \verb`\sqrt`, +\begin{centred} +\verb`\eval{$ \sqrt[3]{-125} $}` $\Longrightarrow$ \eval{$ \sqrt[3]{-125} $}, + +\verb`\eval{$ \sqrt[3]{-1.25} $}` $\Longrightarrow$ \eval{$ \sqrt[3]{-0.125} $}. +\end{centred} + +\subsubsection{Inverse integer powers } + +Of course to find an $n$-th root we can also raise to the inverse +power, +\begin{centred} +\verb`\eval{$ 81^{1/4} $}` $\Longrightarrow$ \eval{$ 81^{1/4} $}. +\end{centred} +However, raising a \emph{negative} number to an inverse power generates +an error even when, mathematically, it should not. This matter is +discussed below in §\ref{subsec:errorsInverse-powers}. + +\subsection{Precedence, parentheses} + +The usual precedence rules apply: multiplication and division bind +equally strongly and more strongly than addition and subtraction which +bind equally stongly. Exponentiating binds most strongly. Evaluation +occurs from the left. +\begin{centred} +\verb`\eval{$ 4+5\times6+3 $}` $\Longrightarrow$ \eval{$ 4+5\times6+3 $}, + +\verb`\eval{$ 6\times10^3/2\times10^2 $}` $\Longrightarrow$ \eval{$ 6\times10^3/2\times10^2 $}, +\end{centred} +which may not be what was intended. Parentheses (or brackets or braces) +retrieve the situation: +\begin{centred} +\verb`\eval{$ (4+5)(6+3) $}` $\Longrightarrow$ \eval{$ (4+5)(6+3) $}, + +\verb`\eval{$ (6\times10^3)/(2\times10^2) $}` $\Longrightarrow$ +\eval{$ (6\times10^3)/(2\times10^2) $}. +\end{centred} +Because exponentiating binds most strongly, negative values must be +parenthesized when raised to a power. If not, +\begin{centred} +\verb`\eval{$ -4^2 $}` $\Longrightarrow$ \eval{$ -4^2 $}, +\end{centred} +which is clearly not $(-4)^{2}$. But +\begin{centred} +\verb`\eval{$ (-4)^2 $}` $\Longrightarrow$ \eval{$ (-4)^2 $}. +\end{centred} + +\subsubsection{Command-form brackets} + +\label{subsec:evalCommandBrackets}Note that brackets of all three +kinds are available also in command form: \verb`\lparen \rparen` +(from \verb`mathtools`) for \verb`( )`, \verb`\lbrack \rbrack` +for \verb`[ ]`, and \verb`\lbrace \rbrace` for \verb`\{ \}`. + +\subsection{Modifiers\texttt{ (\textbackslash left \textbackslash right}, etc.)} + +The \verb`\left` and \texttt{\textbackslash right} modifiers and +also the series of \verb`\big...` modifiers\texttt{ }(\texttt{\textbackslash}\verb`bigl \bigr`, +\verb`\Bigl \Bigr`, \verb`\biggl \biggr`, \verb`\Biggl \Biggr`) +are available for use with all brackets (parentheses, square brackets, +braces): +\begin{verbatim} + \eval[p=.]{\[ \exp\left( + \dfrac{\ln2}{4}+\dfrac{\ln8}{4} + \right) \]} +\end{verbatim} +$\Longrightarrow$ \eval[p=.]{\[ \exp\left( \dfrac{\ln2}{4}+\dfrac{\ln8}{4} \right) \]} + +\texttt{numerica} also accepts their use with \texttt{.} (dot) and +with \texttt{/} (as noted earlier, the \verb`[p]` and \verb`[p=.]` +are explained at §\ref{subsec:settingsPunctuation}): +\begin{centred} +\verb`\eval[p]{\[ \left.\dfrac{3+4}{2+1}\right/\!\dfrac{1+2}{4+5} \]}` +$\Longrightarrow$ \eval[p=.]{\[ \left. \dfrac{3+4}{2+1} \right/\!\dfrac{1+2}{4+5} \]} +\end{centred} +They can be nested. + +\subsection{Other formatting commands} + +\label{subsec:evalFormatting-commands}There are many formatting commands +which change the layout of a formula on the page but do not alter +its content. These include various spacing commands like \verb`\!`, +\verb`\quad`, etc., phantoms (\verb`\phantom` etc.), \verb`\mathstrut` +from \TeX{} and its \verb`mathtools` cousin \verb`\xmathstrut`. + +Consider the same package's \verb`\splitfrac` and \verb`\splitdfrac`. +The \verb`mathtools` documentation gives an example to illustrate +the use of these last two. I've mangled it to produce a ridiculous +illustration of their use, and of the modifiers \verb`\left \right`, +and of the command-form alternatives to parentheses \verb`\lparen \rparen`; +also the use of \verb`\dfrac`. A little mental arithmetic will convince +that we are evaluating the square root of $(9\times7)^{2}$ which +indeed is what we get:\footnote{For the \texttt{{[}p=.,vvd={]}} see §\ref{subsec:settingsPunctuation} +and §\ref{subsec:settingsVvDisplayChangeLocal}. The first puts the +concluding full stop in the right place; the second suppresses the +vv-list.} \medskip{} +\begin{verbatim} + \eval[p=.,vvd=]{\[ + \sqrt{\left\lparen + \frac{ \splitfrac{xy + xy + xy + xy + xy} + {+ xy + xy + xy + xy} + } + { \dfrac z7} + \right\rparen \left\lparen + \frac{ \splitdfrac{xy + xy + xy + xy + xy} + {+ xy + xy + xy + xy} + } + {\dfrac z7}\right\rparen} + \]}[x=2,y=5,z=10] +\end{verbatim} +$\Longrightarrow$\eval[p=.,vvd=]{\[ + \sqrt{\left\lparen + \frac{ \splitfrac{xy + xy + xy + xy + xy} + {+ xy + xy + xy + xy} + } + { \dfrac z7} + \right\rparen \left\lparen + \frac{ \splitdfrac{xy + xy + xy + xy + xy} + {+ xy + xy + xy + xy} + } + {\dfrac z7}\right\rparen} + \]}[x=2,y=5,z=10]\texttt{numerica} essentially ignores formatting commands (the ones +it knows of). They do not alter the mathematical content of a formula, +only how it looks. But there will undoubtedly be formatting commands +it does not recognize which will probably trigger an `Unknown token' +message. Please contact the author in that case.\footnote{ajparsloe@gmail.com} + +\subsection{Trigonometric \& hyperbolic functions} + +\LaTeX{} provides all six trignometric functions, \verb`\sin`, \verb`\cos`, +\verb`\tan`, \verb`\csc`, \verb`\sec`, \verb`\cot` and the three +principal inverses \verb`\arcsin`, \verb`\arccos`, \verb`\arctan`. +It also provides four of the six hyperbolic functions: \verb`\sinh`, +\verb`\cosh`, \verb`\tanh`, \verb`\coth`, and \emph{no} inverses. +\texttt{numerica} provides the missing hyperbolic functions, \verb`\csch` +and \verb`\sech`, and all missing inverses, the three trigonometric +and all six hyperbolic: \verb`\arccsc`, \verb`\arcsec`, \verb`\arccot`, +and \verb`\asinh`, \verb`\acosh`, \verb`\atanh`, \verb`\acsch`, +\verb`\asech`, \verb`\acoth`. (\emph{HMF} writes $\text{arcsinh}$, +$\text{arccosh}$, etc. and ISO recommends $\text{arsinh}$, $\text{arcosh}$, +etc. The first seems ill-advised, the second not widely adopted. At +present neither is catered for in \texttt{numerica}.)\emph{ } +\begin{centred} +\verb`\eval{$ \arctan1/1\deg $}` $\Longrightarrow$ \eval{$ \arctan 1/1\deg $} , + +\verb`\eval{$ \atanh\tanh3 $}` $\Longrightarrow$ \eval{$ \atanh\tanh3 $} . +\end{centred} +Inverses can also be constructed using the `$-1$' superscript notation. +Thus +\begin{centred} +\verb`\eval{$ \sin^{-1}(1/\surd2)/1\deg $}` $\Longrightarrow$ \eval{$ \sin^{-1}(1/\surd2)/1\deg $} , + +\verb`\eval{$ \tanh\tanh^{-1}0.5 $}` $\Longrightarrow$ \eval{$ \tanh\tanh^{-1}0.5 $} . +\end{centred} +\noindent\begin{minipage}[t]{1\columnwidth}% +\begin{shaded}% + +\subsubsection*{Hyperbolic functions} + +Please note that \texttt{l3fp} does not (as yet) provide \emph{any} +hyperbolic functions natively. The values \texttt{numerica} provides +for these functions are \emph{calculated} values using familiar formulas +involving exponentials (for the direct functions) and natural logarithms +and square roots for the inverses. Rounding errors mean the values +calculated may not have $16$-figure accuracy. The worst `offenders' +are likely to be the least used, \verb`\acsch` and \verb`\asech`. +For instance, +\[ +\acsch x=\ln\left[\frac{1}{x}+\left(\frac{1}{x^{2}}+1\right)^{1/2}\right], +\] + +\begin{centred} +\verb`\eval{$ \csch \acsch 7 $}[16]` $\Longrightarrow$ \eval{$ \csch \acsch 7 $}[16]. +\end{centred} +\end{shaded}% +\end{minipage} + +\subsection{Logarithms} + +The natural logarithm \verb`\ln`, base $10$ logarithm \verb`\lg`, +and binary or base $2$ logarithm \verb`\lb` are all recognized, +as is \verb`\log`, preferably with a subscripted base: +\begin{centred} +\verb`\eval{$ \log_{12}1728 $}` $\Longrightarrow$ \eval{$ \log_{12}1728 $} +\end{centred} +If there is no base indicated, base $10$ is assumed. (The notations +\verb`\ln`, \verb`\lg`, and \verb`\lb` follow ISO 80000-2 recommendation, +which frowns upon the use of the unsubscripted \verb`\log` although +only \verb`\ln` appears widely used.) The base need not be explicitly +entered as a number. It could be entered as an expression or be specified +in the vv-list: +\begin{centred} +\verb`\eval*{$ \log_b c $}[b=2,c=1024]` $\Longrightarrow$ \eval*{$ \log_b c $}[b=2,c=1024], +\end{centred} +the log to base $2$ in this case. It is possible to use the unadorned +\verb`\log` with a base different from $10$; if you wish to do this +only for a particular calculation see §\ref{subsec:settingsLogBase}, +or see §\ref{sec:settingsDefaults} if you want to make this default +behaviour. + +\subsection{Other unary functions} + +Other unary functions supported are the exponential function \verb`\exp` +and signature function \verb`\sgn` (equal to $-1$, $0$, or $1$ +depending as its argument is $<0$, $=0$, or $>0$). + +\subsection{Squaring, cubing, \ldots unary functions} + +\texttt{numerica} has no difficulty reading a familiar but `incorrectly +formed' expression like +\[ +\sin^{2}1.234+\cos^{2}1.234. +\] +You do not have to render it $(\sin1.234)^{2}+(\cos1.234)^{2}$ or +(heaven forbid) $(\sin(1.234))^{2}+(\cos(1.234))^{2}$. The everyday +usage is fine: +\begin{centred} +\verb`\eval{$ \sin^2\theta+\cos^2\theta $}[\theta=1.234]` $\Longrightarrow$ +\eval{$ \sin^2\theta+\cos^2\theta $}[\theta=1.234] . +\end{centred} +Equally \texttt{numerica} has no difficulty reading the `correct' +but pedantic form +\begin{centred} +\verb`\eval{$ (\sin(\theta))^2+(\cos(\theta))^2 $}[\theta=1.234]` +$\Longrightarrow$ \eval{$ (\sin(\theta))^2+(\cos(\theta))^2 $}[\theta=1.234] . +\end{centred} +A hyperbolic identity is confirmed in this example: +\begin{centred} +\verb`\eval{$ \sinh 3x $}[x=1]` $\Longrightarrow$ \eval{$ \sinh 3x $}[x=1],\medskip{} + +\verb`\eval{$ 3\sinh x+4\sinh^3x $}[x=1]` $\Longrightarrow$ \eval{$ 3\sinh x+4\sinh^3x $}[x=1]. +\end{centred} +In fact all named unary functions in \texttt{numerica} can be squared, +cubed, etc., in this `incorrect' but familiar way, although the +practice outside the trigonometric and hyperbolic context seems (vanishingly?) +rare. + +When the argument of the function is parenthesized and raised to a +power – like $\sin(\pi)^{2}$ – it is read by \texttt{numerica} as +the `sine of the square of pi', $\sin(\pi^{2})$, and \emph{not +}as the `square of the sine of pi', $(\sin\pi)^{2}$: +\begin{centred} +\verb`\eval{$ \sin(\pi)^2 $}` $\Longrightarrow$ \eval{$ \sin(\pi)^2 $} . +\end{centred} +Things are done like this in \texttt{numerica} above all to handle +the logarithm in a natural way. Surely $\ln x^{n}=n\ln x=\ln(x^{n})$ +rather than $(\ln x)^{n}$? And if we wish to write (as we do) $\ln(1+1/n)^{n}=n\ln(1+1/n)=1-1/2n+1/3n^{2}-\ldots$ +to study the limiting behaviour of $(1+1/n)^{n}$, then we cannot +avoid $\ln(x)^{n}=n\ln(x)=\ln(x^{n})$. + +\subsection{\emph{n}-ary functions} + +The functions of more than one variable ($n$-ary functions) that +\texttt{numerica} supports are \verb`\max`, \verb`\min` and \verb`\gcd`, +greatest common divisor. The comma list of arguments to \verb`\max`, +\verb`\min` or \verb`\gcd` can be of arbitrary length. The arguments +themselves can be expressions or numbers. For \verb`\gcd`, non-integer +arguments are truncated to integers. Hence both $y$ and $3y$ are +independently truncated in the following example – to $81$ and $243$ +respectively: +\begin{centred} +\verb`\eval{$ \gcd(12,10x^2,3y,y,63) $}[y=1/0.0123456789,x=3]` $\Longrightarrow$ +\eval{$ \gcd(12,10x^2,3y,y,63) $}[y=1/0.0123456789,x=3] . +\end{centred} +(The truncation occurs in the argument of \verb`\gcd`, not in the +vv-list.) + +For $n$-ary functions, squaring, cubing, etc. follows a different +pattern from that for unary functions. For \verb`\max`, \verb`\min`, +\verb`\gcd` the argument of the function is a comma list. Squaring +the argument makes no sense. We understand the superscript as applying +to the function as a whole. (Consistency is not the point here; it +is what mathematicians do that \texttt{numerica} tries to accommodate.) +\begin{centred} +\verb`\eval{$ \gcd(3x,x,\arcsin 1/\deg)^2 $}[x=24]` $\Longrightarrow$ +\eval{$ \gcd(3x,x,\arcsin 1/\deg)^2 $}[x=24] . +\end{centred} + +\subsection{Delimiting arguments with brackets \& modifiers } + +Arguments of unary and $n$-ary functions can be delimited not only +with parentheses, but also with square brackets and braces, both in +explicit character form and also in the command form of §\ref{subsec:evalCommandBrackets}. +The brackets, of whatever kind, can be qualified with \verb`\left \right`, +\verb`\bigl \bigr`, etc.\footnote{See §\ref{subsec:settingsPunctuation} for the \texttt{{[}p=.{]}} +(which ensures the concluding full stop appears in the correct place.} +\begin{centred} +\verb`\eval[p=.]{\[ \sin\left\lbrack \dfrac\pi{1+2+3}\right\rbrack \]}` +$\Longrightarrow$\eval[p=.]{\[ \sin\left\lbrack\dfrac\pi{1+2+3}\right\rbrack \]} +\end{centred} + +\subsection{Absolute value, floor \& ceiling functions} + +It is tempting to use the \texttt{|} key on the keyboard for inserting +an absolute value sign. \texttt{numerica} accepts this usage, but +it is deprecated. The spacing is incorrect – compare $|-l|$ using +\texttt{|} against $\lvert-l\rvert$ using \verb`\lvert \rvert`. +Also, the identity of the left and right delimiters makes nested absolute +values difficult to parse. \texttt{numerica} does not attempt to do +so. Placing an absolute value constructed with \texttt{|} within another +absolute value constructed in the same way is likely to produce a +compilation error or a spurious result. \verb`\lvert \rvert` are +better in every way except ease of writing.\texttt{ }To aid such ease +\texttt{numerica }provides the \verb`\abs` function (using the \texttt{\textbackslash DeclarePairedDelimiter} +command of the \texttt{mathtools} package). This takes a mutually +exclusive star (asterisk) or square bracketed optional argument, and +a mandatory braced argument. The starred form expands to \verb`\left\lvert #1 \right\rvert` +where \verb`#1` is the mandatory argument: +\begin{centred} +\verb`\eval[p=.]{\[ 3\abs*{\frac{\abs{n}}{21}-1} \]}[n=-7]` $\Longrightarrow$ +\eval[p=.]{\[ 3\abs*{\frac{\abs{n}}{21}-1} \]}[n=-7] +\end{centred} +The optional argument provides access to the \verb`\big...` modifiers: +\begin{verbatim} + \eval[p=.]{\[ + \abs[\Big]{\abs{a-c}-\abs[\big]{A-C}} + \]}[A=12,a=-10,C=7,c=-5] +\end{verbatim} +$\Longrightarrow$ \eval[p=.]{\[ + \abs[\Big]{\abs{a-c}-\abs[\big]{A-C}} + \]}[A=12,a=-10,C=7,c=-5] + +The form without either star or square bracket option dispenses with +the modifiers altogether: +\begin{centred} +\verb`\eval{$ \tfrac12(x+y)+\tfrac12\abs{x-y} $}[x=-3,y=7].` $\Longrightarrow$ +\eval{$ \tfrac12(x+y)+\tfrac12\abs{x-y} $}[x=-3,y=7]. +\end{centred} +As noted, the star and square bracketed option are mutually exclusive +arguments. + +\texttt{numerica} also provides the functions \verb`\floor` and \verb`\ceil`, +defined in the same way, taking a mutually exclusive star or square +bracketed optional argument and for the starred forms expanding to +\verb`\left\lfloor #1 \right\rfloor` and \verb`\left\lceil #1 \right\rceil` +where \verb`#1` is the mandatory argument, and for the square bracket +option forms replacing the \verb`\left` and \verb`\right` with the +corresponding \verb`\big` commands. The form without star or square-bracket +option dispenses with any modifier at all. +\begin{centred} +\verb`\eval{$ \floor{-\pi} $}` $\Longrightarrow$ \eval{$ \floor{-\pi} $}, + +\verb`\eval{$ \ceil{\pi} $}` $\Longrightarrow$ \eval{$ \ceil{\pi} $}. +\end{centred} +The floor function, $\lfloor x\rfloor$, is the greatest integer $\le x$; +the ceiling function, $\lceil x\rceil$ is the smallest integer $\ge x$. +Like the absolute value, the floor and ceiling functions, can be nested: +\begin{centred} +\verb`\eval{$ \floor{-\pi+\ceil{e}} $}` $\Longrightarrow$ \eval{$ \floor{-\pi+\ceil{e}} $}. +\end{centred} + +\subsubsection{Squaring, cubing, \ldots{} absolute values, etc.} + +These three functions can be raised to a power \emph{without} extra +parentheses: +\begin{centred} +\verb`\eval{$ \ceil{e}^2 $},` $\Longrightarrow$ \eval{$ \ceil{e}^2 $}, + +\verb`\eval{$ \abs{-4}^2 $}.` $\Longrightarrow$ \eval{$ \abs{-4}^2 $}. +\end{centred} + +\subsection{Factorials, binomial coefficients} + +\label{subsec:evalFactorialsBinom}Factorials use the familiar trailing +\texttt{!} notation: +\begin{centred} +\verb`\eval{$ 7! $}` $\Longrightarrow$ \eval{$ 7! $}, + +\verb`\eval{$ (\alpha+\beta)!-\alpha!-\beta! $}[\alpha=2,\beta=3]` +$\Longrightarrow$ \eval{$ (\alpha+\beta)!-\alpha!-\beta! $}[\alpha=2,\beta=3]. +\end{centred} +The examples illustrate how \texttt{numerica} interprets the argument +of the factorial symbol:\texttt{ }it `digests' +\begin{enumerate} +\item a preceding (possibly multi-digit) integer, or +\item a preceding variable token, or +\item a bracketed expression, or +\item a bracket-like expression – an absolute value, floor or ceiling function, +\end{enumerate} +since they delimit arguments in a bracket-like way: +\begin{centred} +\verb`\eval{$ \abs{-4}!+\floor{\pi}!+\ceil{e}! $}` $\Longrightarrow$ +\eval{$ \abs{-4}!+\floor{\pi}!+\ceil{e}! $}. +\end{centred} +The result of feeding the factorial an expression different in kind +from one of these four cases may give an error message or an unexpected +result. Use parentheses around such an expression; for example write +$(3^{2})!$, rather than $3^{2}!$. + +Nesting of brackets for factorials is accepted: +\begin{centred} +\verb`\eval{$ ((5-2)!+1)! $}` $\Longrightarrow$ \eval{$ ((5-2)!+1)! $}. +\end{centred} +The factorials of negative integers or of non-integers are not defined +in \texttt{numerica}. Again there is the problem met in relation to +$n$-th roots of what happens if the argument of a factorial is the +result of a calculation and rounding errors mean it is not an exact +integer. This problem is unlikely to be of practical concern since +\texttt{numerica} rounds the result of such a calculation by default +to $14$ significant figures before offering it to the factorial. +Since \texttt{l3fp} works to $16$ significant figures, there is ample +`elbowroom' to accommodate rounding errors before the result of +a calculation ceases to round to an integer. + +\subsubsection{Double factorials} + +The double factorial, written $n!!,$ is the product $n(n-2)(n-4)\ldots\times4\times2$ +when $n$ is even and the product $n(n-2)(n-4)\ldots\times3\times1$ +when $n$ is odd. +\begin{centred} +\verb`\eval{$ 6!! $}` $\Longrightarrow$ \eval{$ 6!! $}, + +\verb`\eval{$ n!! $}[n=\sqrt{49}]` $\Longrightarrow$ \eval{$ n!! $}[n=\sqrt{49}], +\end{centred} +Since $n!=n!!(n-1)!!$ it follows that +\[ +n!!=\frac{n!}{(n-1)!!}=\frac{(n+1)!}{(n+1)!!}. +\] +Putting $n=0$ in the outer equality shows that $0!!=1$. Now putting +$n=0$ in the left equality gives $(-1)!!=1$. Double factorials therefore +are defined for integers $\ge-1$. + +\subsubsection{Binomial coefficients} + +Binomial coefficients are entered in \LaTeX{} with the \verb`\binom`\textbf{ +}command. It takes two arguments and has a text-style version \verb`\tbinom` +and a display-style version \verb`\dbinom`. As implemented in \texttt{numerica}, +these are \emph{generalised} binomial coefficients: +\[ +\binom{x}{k}=\frac{x(x-1)\dots(x-k+1)}{k(k-1)\dots1},\quad(x\in\mathbb{R},~k\in\mathbb{N}), +\] +where $x$ need not be a non-negative integer, and where $\binom{x}{0}=1$ +by definition. Although the first (or upper) argument can be any real +number, the lower argument \emph{must} be a non-negative integer. +Thus, \verb`\eval{$ \tbinom53 $}` $\Longrightarrow$ \eval{$\tbinom53$}, +\verb`\eval{$ \tbinom70 $}` $\Longrightarrow$ \eval{$\tbinom70$}, +\verb`\eval{$ \tbinom{4.2}3 $}` $\Longrightarrow$ \eval{$\tbinom{4.2}3$}, +but if the second (or lower) argument of \verb`\binom` is \emph{not} +a non-negative integer, \texttt{numerica} displays a message; see +§\ref{subsec:errorsIntegerArgs}. + +\subsection{Sums and products} + +\texttt{numerica} recognizes sums (\verb`\sum` displaying as $\sum$) +and products (\verb`\prod` displaying as $\prod$), and expects both +symbols to have lower and upper summation/product limits specified. +The lower limit must be given in the form \emph{sum/prod variable += initial value}; the upper limit requires only the final value to +be specified (although it can also be given in the form \emph{sum/prod +variable = final value}). The values may be expressions depending +on other variables and values but must evaluate to integers (or infinity +– see §\ref{sec:settingsInfiniteSumsProds}). Evaluating to an integer +means that they \emph{round} to an integer, using a rounding value +that is set by default to $14$; (recall that \texttt{l3fp} works +to $16$ significant figures). If a limit evaluates to a non-integer +at this `int-ifying' rounding value, an error message results. (To +change this `int-ifying' rounding value, see §\ref{subsec:defaultsIntifyingRounding}.) + +As an example of expressions in the limits, this example uses the +floor and ceiling functions to convert combinations of constants to +integers (the \verb`[p]` is explained in §\ref{subsec:settingsPunctuation}), +\begin{centred} +\verb`\eval[p]{\[ \sum_{n=\floor{\pi/e}}^{\ceil{\pi e}}n \]}` $\Longrightarrow$\eval[p]{\[ \sum_{n=\floor{\pi/e}}^{\ceil{\pi e}}n \]} +\end{centred} +\noindent (which is $\sum_{n=1}^{9}n$).\emph{ }If the upper limit +is less than the lower limit the result is zero. Notice that there +is no vv-list. The summation variable does not need to be included +there unless there are other variables that depend on it. However, +in the case +\begin{centred} +\verb`\eval[p]{\[ \sum_{k=1}^N\frac1{k^3} \]}[N=100][4]` $\Longrightarrow$ +\eval[p]{\[ \sum_{k=1}^N\frac1{k^3} \]}[N=100][4] +\end{centred} +the upper limit $N$ is necessarily assigned a value in the vv-list. + +To the author it seems natural to enter the lower limit first, immediately +after the \verb`\sum` command (the sum is \emph{from }something \emph{to} +something), but no problem will accrue if the upper limit is placed +first (after all, the appearance of the formula in the pdf is the +same): +\begin{centred} +\verb`\eval[p=.]{\[ \sum^N_{k=1}\frac1{k^3} \]}[N=100][4]` $\Longrightarrow$ +\eval[p=.]{\[ \sum^N_{k=1}\frac1{k^3} \]}[N=100][4] +\end{centred} +Another example of a sum, using binomial coefficients this time, is +\begin{centred} +\verb`\eval[p]{\[ \sum_{m=0}^5\binom{5}{m}x^m y^{5-m} \]}[x=0.75,y=2.25]` +$\Longrightarrow$ \eval[p]{\[ \sum_{m=0}^5\binom{5}{m}x^m y^{5-m} \]}[x=0.75,y=2.25] +\end{centred} +which is just \verb`\eval{$(x+y)^5$}[x=0.75,y=2.25]` $\Longrightarrow$ +\eval{$ (x+y)^5 $}[x=0.75,y=2.25], or $3^{5}$. + +Now let's calculate a product: +\begin{verbatim} + \eval[p]{\[ + \prod_{k=1}^{100} + \biggl(\frac{x^2}{k^2\pi^2} +1\biggr) + \]}[x=1][3] +\end{verbatim} +$\Longrightarrow$ \eval[p]{\[\prod_{k=1}^{100} \biggl(\frac{x^2}{k^2\pi^2} +1\biggr)\]}[x=1][3] + +\noindent to be compared with \verb`\eval{$ \sinh 1 $}[3]` $\Longrightarrow$ +\eval{$ \sinh1 $}[3]. Obviously more terms than $100$ are required +in the product to achieve 3-figure accuracy. + +\subsubsection{Infinite sums and products} + +There is a strong urge to use $\infty$ in the upper limit of this +product. Let's do so: +\begin{verbatim} + \eval[p=.]{\[ + \prod_{k=1}^{\infty} + \biggl(\frac{x^2}{k^2\pi^2} +1\biggr) + \]}[x=1][3] +\end{verbatim} +$\Longrightarrow$ \eval[p=.] + {\[ + \prod_{k=1}^{\infty} + \biggl(\frac{x^2}{k^2\pi^2} +1\biggr) + \]}[x=1][3] + +\noindent Disappointingly, we still get the same result, deficient +by $1$ in the third decimal place. Obviously \texttt{numerica} has +not multiplied an infinite number of terms and, just as obviously, +the finite number of terms it \emph{has} multiplied are too few. How +\texttt{numerica} decides when to stop evaluating additional terms +in an infinite sum or product is discussed later, §\ref{sec:settingsInfiniteSumsProds}. + +For this particular product the problem is that it converges slowly. +Any criterion for when to stop multiplying terms or, for an infinite +sum adding terms, seems bound to fail for some product or series. +Presumably any stopping criterion must measure smallness in some way. +But terms of the divergent harmonic series, $\sum(1/n)$ can always +be found smaller than any value we care to specify. It is not surprising +that a sufficiently slowly converging product or series falls foul +of a given criterion. + +The default criterion however can be changed. Because this involves +values assigned in the settings option of the \verb`\eval` command, +I discuss infinite sums and products in the section discussing that +optional argument; see §\ref{sec:settingsInfiniteSumsProds}. + +Other infinite sums converge more rapidly, and the default settings +work admirably. For example \verb`\eval{$ (1+0.1234)^{4.321} $}` +$\Longrightarrow$ \eval{$ (1+0.1234)^{4.321} $}. Using binomial +coefficients we can express this as an infinite sum:\medskip{} +\begin{verbatim} + \eval[p=.]{\[ + \sum_{n=0}^{\infty}\binom{\alpha}{n}x^{n} + \]}[\alpha=4.321,x=0.1234] +\end{verbatim} +$\Longrightarrow$ \eval[p=.] + {\[ + \sum_{n=0}^{\infty}\binom{\alpha}{n}x^{n} + \]}[\alpha=4.321,x=0.1234] + +\section{Error messages } + +\label{sec:evalErrors}There are two kinds of error in \texttt{numerica}: +those in the underlying \LaTeX{} which are reported in the \LaTeX{} +log, shown on the terminal, and generally halt compilation, and specifically +\texttt{numerica}-related errors which do not halt compilation and +produce messages displayed in the pdf where one would expect the result +of the calculation to be. The original reason for doing things this +way was to enable \texttt{numerica} to be used effectively with the +instant preview facility of the document processor \LyX . More philosophically, +one might view such errors as similar to grammatical errors or spelling +mistakes in text. It is not clear that they should halt compilation. +Hence strictly \texttt{numerica}-related errors leave brief messages +in the pdf at the offending places. + +Before discussing specific error messages, note that there is a debug +facility (of a sort) discussed below in §\ref{subsec:settingsDebug}. + +Error messages are in two parts: a \emph{what} part and a \emph{where} +part. + +\subsection{Mismatched brackets} + +\label{subsec:errorsMismatched-brackets}An unmatched left parenthesis +or other left bracket (in this case a missing right parenthesis) usually +results in a \texttt{numerica} error: +\begin{centred} +\verb`$\eval{\sin(\pi/(1+x)}[x=1]$` $\Longrightarrow$ $\eval{\sin(\pi/(1+x)}[x=1]$ +\end{centred} +For the same error in the vv-list, the what-part remains unchanged +but the where-part is altered: +\begin{centred} +\verb`$\eval{ 1+y }[x=1,y=\sin(\pi/(1+x)]$` $\Longrightarrow$ $\eval{ 1+y }[y=\sin(\pi/(1+x),x=1]$ +\end{centred} +The \emph{what} message is the same; the \emph{where} is different. + +An unmatched right parenthesis or other right bracket (in this case +a missing \emph{left} parenthesis) usually results in a similar \texttt{numerica} +error: +\begin{centred} +\verb`$\eval{2((x+y)/(y+z)))^2}[x=1,y=2,z=3]$` $\Longrightarrow$ +\eval{2((x+y)/(y+z)))^{2}}[x=1,y=2,z=3] +\end{centred} +But note that an unmatched modifier like \verb`\left` or \verb`\right` +is a \LaTeX{} error and is caught by \LaTeX{} before \texttt{numerica} +can respond and so results in a terminal and logfile message. + +\subsection{Unknown tokens} + +An `Unknown token' message can arise in a number of ways. If an +expression involves a number of variables, some of which depend on +others, their order in the vv-list matters: +\noindent \begin{center} +\verb`$\eval{\tfrac12 vt}[t=2,v=gt,g=9.8]$` $\Longrightarrow$ \eval{\tfrac{1}{2}vt}[t=2,v=gt,g=9.8] +\par\end{center} + +The vv-list is evaluated from the \emph{right} so that in this example +the variable \texttt{v} depends on a quantity \texttt{t} that is not +yet defined. Hence the message. The remedy is to move \texttt{t} to +the right of \texttt{v} in the vv-list. + +Similarly, if we use a variable in the formula that has not been assigned +a value in the vv-list, we again get the `Unknown token' message, +but this time the location is the formula: +\begin{centred} +\verb`$\eval{\pi r^2h}[r=3]$` $\Longrightarrow$ \eval{\pi r^{2}h}[r=3] +\end{centred} +The remedy obviously is to assign a value to \texttt{h} in the vv-list\texttt{.} + +The same message will result if a mathematical operation or function +is used that has not been implemented in \texttt{numerica}: +\begin{centred} +\verb`$\eval{u \bmod v }[v=7,u=3]$` $\Longrightarrow$ \eval{u\bmod v}[v=7,u=3] +\end{centred} +A missing comma in the vv-list will generally result in an unknown +token message: +\begin{centred} +\verb`$\eval{axy}[a=3 y=2,x=1]$` $\Longrightarrow$ \eval{axy}[a=3y=2,x=1] +\end{centred} +Because of the missing comma, \texttt{numerica} assumes \texttt{a} +has the `value' \texttt{3y=2} and has no knowledge of \texttt{y} +as a variable. + +The presence of multi-token variables can also cause this error message +if the check for such variables is turned off; see §\ref{subsec:settingsMultitokSwitch}. + +\subsection{Other vv-list errors} + +Other errors that can occur with the vv-list are overlooked value +assignments to variables, or missing commas. For the first, it is +essential that we do actually give a value to all variables occuring +in the vv-list: +\begin{centred} +\verb`$\eval{axy}[a=3,y=,x=1]$` $\Longrightarrow$ \eval{axy}[a=3,y=,x=1] +\end{centred} +The remedy is obvious – assign a value to \texttt{$y$}. + +\emph{Extra} commas in the vv-list should cause no problems: +\begin{centred} +\verb`$\eval{axy}[,a=3,,y=2,x=1,]$` $\Longrightarrow$ $\eval{axy}[,a=3,,y=2,x=1,]$ +\end{centred} + +\subsection{Inverse powers of negative numbers} + +\label{subsec:errorsInverse-powers}Inverse integer powers of positive +numbers should always be possible, but raising a \emph{negative} number +to an inverse power generates an error even when, mathematically, +it should not: +\begin{centred} +\verb`\eval{$ (-125)^{1/3} $}` $\Longrightarrow$ \eval{$ (-125)^{1/3} $} +\end{centred} +This is a feature of floating point arithmetic. When a number is raised +to a rational power, say $p/q$ where $p$ and $q$ are non-zero integers, +then the result is the $p$-th power of the $q$-th root of the number. +Can a $q$-th root be taken? If our floating point system used (for +ease of illustration) only $4$ significant digits, $p/q=1/3$ would +be the fraction $3333/10^{4}$, an odd numerator over an even denominator. +But a negative number does not possess an even ($10^{4}$-th) root. + +\subsection{Integer argument errors} + +\label{subsec:errorsIntegerArgs}Some functions require integer arguments +– factorials, the second argument of a binomial coefficient, and (in +\texttt{numerica}) $n$-th roots using the optional argument of \texttt{\textbackslash sqrt}; +also summation and product variables. If integers are explicitly entered +for these arguments there is no problem, but if the value of the argument +is the result of a calculation, rounding errors require thinking about. +What accumulation of rounding errors is \emph{too} much so that the +result of the calculation \emph{cannot} be considered an integer? +\texttt{numerica} is generous: in the default setup, if a calculation +rounds to an integer at rounding value $14$ the result of the calculation +is considered an integer (obviously, the integer resulting from the +rounding). Since \texttt{l3fp} works to $16$ significant figures +that gives ample room for rounding errors to `get lost in' and be +ignored, while still ruling out such things as (recall the example +in §\ref{subsec:evalBoolean-output}), +\begin{centred} +\verb`\eval{\[ \sum_{n=1}^N n \]}[N=1/0.0123456789]` $\Longrightarrow$ +\eval{\[ \sum_{n=1}^N n \]}[N=1/0.0123456789] +\end{centred} +where $N$ differs from $81$ not until the seventh decimal place. + +The default rounding value of $14$ for `int-ifying' calculations +can be changed: see §\ref{subsec:defaultsIntifyingRounding}. + +\subsection{Comparison errors} + +Should a user try to make a comparison using a combination like \verb`>=` +rather than \verb`\geq`, \texttt{numerica} admonishes like this: +\begin{centred} +\verb`$\eval{ \pi^e >= e^\pi }[?]$` $\Longrightarrow$ $\eval{ \pi^e >= e^\pi }[?]$ +\end{centred} +(The relation is false by the way.) + +\subsection{Invalid base for \texttt{\textbackslash log}} + +ISO recommends using \verb`\log` only with a subscripted base specified. +Otherwise how is one to know whether the base is \verb`e` or $10$ +or $2$ or whatever? Nonetheless \texttt{numerica} assumes that when +\verb`\log` is used unsubscripted, the base is 10. Suppose you want +to make $12$ the base, but forget to put braces around the $12$: +\begin{centred} +\verb`$\eval{ \log_12 1728 }$` $\Longrightarrow$ $\eval{ \log_12 1728 }$ +\end{centred} +Here, \texttt{numerica} has taken \texttt{1} as the base (and $21728$ +as the argument) of the logarithm and responds accordingly. + +\subsection{\texttt{l3fp} errors} + +Some errors arising at the \texttt{l3fp} level are trapped and a message +displayed. +\begin{itemize} +\item Dividing by zero +\end{itemize} +\begin{centred} +\verb`$\eval{1/\sin x}[x=0]$` $\Longrightarrow$ \eval{1/\sin x}[x=0] +\end{centred} +Note however that \verb`$\eval{1/\sin x}[x=\pi]$` $\Longrightarrow\,\eval{1/\sin x}[x=\pi]$, +because of rounding errors in distant decimal places. No doubt this +is true for other functions as well. +\begin{itemize} +\item Invalid operation +\end{itemize} +\begin{centred} +\verb`$\eval{\arccos x}[x=2]$` $\Longrightarrow$ \eval{\arccos x}[x=2] +\end{centred} +In this case the inverse cosine has been fed a value of $x$ outside +its domain of definition, the interval $[-1,1]$. Trying to evaluate +an expression that resolves to $0/0$ also produces this message: +\begin{centred} +\verb`$\eval{\frac{1-y}{x-2}}[x=2,y=1]$`$\Longrightarrow$ \eval{\frac{1-y}{x-2}}[x=2,y=1] +\end{centred} +\begin{itemize} +\item Overflow/underflow +\end{itemize} +The factorial (discussed in §\ref{subsec:evalFactorialsBinom}) provides +an example of overflow: +\begin{centred} +\verb`$\eval{3249!}$`\texttt{ }$\Longrightarrow$ \eval{3249!} +\end{centred} +This is hardly surprising since +\begin{centred} +\verb`$\eval{3248!}[x]$` $\Longrightarrow$ $\eval{3248!}[x]$. +\end{centred} +There is a limit on the size of exponents that \texttt{l3fp} can handle. +A number in the form $a\times10^{b}$ must have $-10001\le b<10000$. +If this is not the case an overflow or underflow condition occurs. +As the examples show, an overflow condition generates a \texttt{numerica} +error. For underflow, where the number is closer to $0$ than $10^{-10001}$, +\texttt{l3fp} assigns a zero value to the quantity. \texttt{numerica} +accepts the zero value. + +\chapter{Settings} + +\label{chap:Settings}A calculation is effected against a background +of default values for various quantities. For a particular calculation, +these values may not be appropriate; or you may have different preferences. +The way to change settings for a particular calculation is through +the settings option of \verb`\nmcEvaluate` discussed next. The way +to change a \emph{default} setting is by creating a configuration +file \texttt{numerica.cfg} discussed in §\ref{sec:settingsDefaults}. + +\section{Settings option} + +\label{sec:settingsOption}The second argument of the \verb`\nmcEvaluate` +command is the settings option, delimited by square brackets. This +option is a \emph{key=value} list, hence comma-separated. \emph{Key=value +}lists tend to be wordy. For back-of-envelope calculations one wants +to be able to `dash off' the calculation, hence the short, cryptic +nsture of the keys. Most settings are generic, applicable not only +to \verb`\nmcEvaluate` but also to other commands that are available +if \texttt{numerica} is loaded with the \texttt{plus} option; see +the associated document \texttt{numerica-plus.pdf}. + +\subsection{\textquoteleft Debug\textquoteright{} facility} + +\label{subsec:settingsDebug}It is rather grandiose to call this a +debug facility, but if a calculation goes wrong or produces a surprising +result, \texttt{numerica} offers a means of examining some intermediate +stages on the way to the final result. To use the facility, enter +\begin{lyxcode} +dbg~=~<integer> +\end{lyxcode} +into the settings option. (White space around the equals sign is optional.) +\begin{itemize} +\item \texttt{dbg=0 }turns off the debug function, displays the result or +error message (this is the default); +\item \texttt{dbg=1 }equivalent to \texttt{dbg=2{*}3{*}5{*}7}; +\end{itemize} +The `magic' integers are the following primes and their products: + +\begin{table}[t] +\centering +\noindent \centering{}\caption{Settings options} +\noindent \begin{center} +\begin{tabular}{ll>{\raggedright}p{4cm}>{\raggedright}p{4cm}} +\toprule +{\small key} & {\small type} & {\small meaning} & {\small default}\tabularnewline +\midrule +{\small\texttt{dbg}} & {\small int} & {\small debug `magic' integer} & {\small\texttt{0}}\tabularnewline +{\small\texttt{reuse}} & {\small int} & {\small form of result saved with }{\small{\small\verb`\nmcReuse`}} & {\small\texttt{0}}\tabularnewline +{\small\texttt{\textasciicircum}} & {\small char} & {\small exponent mark for sci. notation input} & {\small\texttt{e}}\tabularnewline +{\small\texttt{xx}} & {\small int (0/1)} & {\small multi-token variable switch} & {\small\texttt{1}}\tabularnewline +{\small\texttt{()}} & {\small int (0/1/2)} & {\small trig. arg. parsing} & {\small\texttt{0}}\tabularnewline +{\small\texttt{o}} & & {\small degree switch for trig. funcions} & \tabularnewline +{\small\texttt{log}} & {\small num} & {\small base of logarithms for }{\small{\small\verb`\log`}} & {\small\texttt{10}}\tabularnewline +{\small\texttt{vvmode}} & {\small int (0/1)} & {\small vv-list calculation mode} & {\small\texttt{0}}\tabularnewline +{\small\texttt{vvd}} & {\small token(s)} & {\small vv-list display-style spec.} & {\small\texttt{\{,\}\textbackslash mskip 12mu plus 6mu minus 9mu(vv)}}\tabularnewline +{\small\texttt{vvi}} & {\small token(s)} & {\small vv-list text-style spec.} & {\small\texttt{\{,\}\textbackslash mskip 36mu minus 24mu(vv)}}\tabularnewline +{*} & & {\small suppress equation numbering if }{\small\texttt{\textbackslash\textbackslash}}{\small{} +in }{\small\texttt{vvd}} & \tabularnewline +{\small\texttt{p}} & token(s) & {\small punctuation (esp. in display-style)} & {\small\texttt{,}}\tabularnewline +\bottomrule +\end{tabular} +\par\end{center} +\end{table} + +\begin{itemize} +\item \texttt{dbg=2} displays the vv-list after multi-token variables have +been converted to their single token form, \texttt{\textbackslash\_nmca}, +\texttt{\textbackslash\_nmcb}, etc.; +\item \texttt{dbg=3} displays the formula after multi-token variables have +been converted to their single token form; +\item \texttt{dbg=5} displays the stored variables and their evaluated values +(\texttt{dbg=2} lists the values as expressions; here they have been +evaluated); note that any saved values (Chapter~\ref{chap:Saving-and-retrieving}) +that have been loaded will also feature in this list which might lead +to a messy display depending on the nature of those values; +\item \texttt{dbg=7} displays the formula after it has been fp-ified (but +before it has been fed to \texttt{l3fp} to evaluate); +\begin{itemize} +\item should the formula successfully evaluate, the result of the evaluation +is also displayed. +\end{itemize} +\end{itemize} +\vspace{-1ex} + +\begin{wraptable}{o}{0.5\columnwidth}% +\centering{}\caption{Magic integers}\label{tab:settingsMagic-integers} +\begin{center} +\begin{tabular}{rrl} +\toprule +integer & & \multicolumn{1}{c}{factors}\tabularnewline +\midrule +6 & & 2,3\tabularnewline +10 & & 2,5\tabularnewline +14 & & 2,7\tabularnewline +15 & & 3,5\tabularnewline +21 & & 3,7\tabularnewline +30 & & 2,3,5\tabularnewline +35 & & 5,7\tabularnewline +42 & & 2,3,7\tabularnewline +70 & & 2,5,7\tabularnewline +105 & & 3,5,7\tabularnewline +210 & & 2,3,5,7\tabularnewline +\bottomrule +\end{tabular} +\par\end{center}\end{wraptable}% +To display two or more of these elements simultaneously, use the product +of their debug numbers for the magic integer. This can be entered +either as the multiplied-out product, or as the `waiting to be evaluated' +product with asterisks (stars) between the factors. Thus \texttt{dbg=6} +or \verb`dbg=2*3` display both the vv-list and formula after multi-token +variables have been converted to single token form; \texttt{dbg=10} +or \verb`dbg=2*5` display both the vv-list after multi-token variables +have been converted to single token form and the recorded variables +with their evaluated values. And similarly for the other magic integers +listed. For other integers, if they are divisible by $2$ or $3$ +or $5$ or $7$, they will display the corresponding component. Both +\texttt{dbg=210} and \verb`dbg=2*3*5*7` display all four elements, +but rather than remembering this product, it suffices to put \texttt{dbg=1}. +This is equivalent and displays all elements. + +The debug option uses an \texttt{aligned }or \texttt{align{*}} environment +to display its wares, depending on the presence or absence of math +delimiters around the \texttt{\textbackslash eval} command. In the +next example I have used multi-token variables to illustrate the different +elements in the debug display, and a chain of comparisons to show +how \texttt{numerica} treats these (§\ref{subsec:evalBoolean-output}). +\begin{verbatim} + \eval[dbg=1]{ a_1<2a_2<3a_3<\pi+e } + [a_1=\pi,a_2=\phi,a_3=e\gamma][6?''] +\end{verbatim} +$\Longrightarrow$ \eval[dbg=1]{ a_1<2a_2<3a_3<\pi+e } + [a_1=\pi,a_2=\phi,a_3=e\gamma][6?''] + +Note that the four elements are displayed in temporal order: first +comes the vv-list after conversion of multi-token to single-token +variables, then the formula in the single-token variables; these are +created essentially at the same time. The vv-list is presented in +left-to-right order because that is the direction of evaluation \emph{internally} +in \texttt{numerica}. Next the stored values of the variables are +displayed. These are the values \emph{after }evaluation. The fourth +element both in the display and chronologically is the fp-ified formula; +this is often a thicket of parentheses. The final element of the display +and chronologically is the result of evaluating the formula. This +is displayed only if $7$ is a factor of the \texttt{dbg} integer, +and there is no error. + +When interpreting the fp-form, one should be aware of differences +between \texttt{numerica} and \texttt{l3fp}. In particular be aware +that in \texttt{l3fp} function calls bind most tightly so that, for +example, \verb`sin 2pi` evaluates not to zero but to $(\sin2)\times\pi$ +and \verb`sin x^2` evaluates to $(\sin x)^{2}$. This should not +be of any concern to the user except as here in debug mode when interpreting +fp-forms. + +Finally, note that those mathematical operations that have no direct +representation in \texttt{l3fp} contribute only their value to the +fp-form. This applies to sums and products, double factorials and +partly to binomial coefficients as illustrated in the followng (ridiculous) +example: +\begin{verbatim} + \eval[dbg=1]{\[ + \sum_{n=1}^5 n + \binom{10}{m} + + \prod_{n=2}^5 (1-1/n) + m!! \][m=6] +\end{verbatim} +$\Longrightarrow$ \eval[dbg=1]{\[ + \sum_{n=1}^5 n+\binom{10}{m} + +\prod_{n=2}^5(1-1/n) +m!! \]}[m=6] + +\noindent The various contributions to the overall result are displayed +simply as numbers because \texttt{l3fp} does not (at least as yet) +handle these elements natively. + +\subsubsection{Negative \texttt{dbg} values} + +Negative \texttt{dbg} values are possible: \texttt{dbg=-2}, \texttt{dbg=-3}, +etc. (and \texttt{dbg=-1} meaning \texttt{dbg=-210}) have exactly +the same effects as the corresponding positive values except for some +details of display. The display for positive \texttt{dbg} values is +the one evident in the examples above. Lines wrap, the left margin +is not indented and the display occupies the page width. For negative +\texttt{dbg} values, lines do not wrap, the left margin is indented +and the display occupies the text width. An example is presented in +§\ref{subsec:nestDebugging} below where the display for a nested +\verb`\eval` is significantly improved with a negative \texttt{dbg} +value. + +\subsection{Reuse setting} + +This setting determines whether the entire display or only the numerical +result is saved to file with the \verb`\nmcReuse` command. See below, +Chapter~\ref{chap:Saving-and-retrieving}, §\ref{subsec:reuse=00005Ceval's-reuse-setting}. + +\subsection{Inputting numbers in scientific notation} + +\label{subsec:settingsInputtingSciNotation}\emph{Outputting} numbers +in scientific notation is controlled by the final trailing argument +of the \texttt{\textbackslash eval} command. That is turned off by +default and needs to be explicitly ordered. Similarly, \emph{inputting} +numbers in scientific notation is turned off by default and needs +to be explicitly ordered. To turn it on, write +\begin{lyxcode} +\textasciicircum ~=~<char> +\end{lyxcode} +\noindent in the settings option, where \texttt{<char>} is any single +character, usually \texttt{e} or \texttt{d} or their upper-casings, +but not restricted to them: \texttt{\textasciicircum =@} for instance +is perfectly possible, and has the advantage over \texttt{e} or \texttt{d} +that it doesn't conflict with the use of the character as a variable +or constant. +\begin{centred} +\verb`$ \eval[^=@]{ 1.23@-1 } $` $\Longrightarrow$ $ \eval[^=@]{ 1.23@-1 } $. +\end{centred} +With letters for the exponent mark – say \verb`d` or \verb`e` – +the problem is interpreting forms like \texttt{8d-3} or \texttt{2e-1}. +Does such a form denote a number in scientific notation or an algebraic +expression? In \texttt{numerica}, if the settings option shows \texttt{\textasciicircum =d}, +then a form like \texttt{8d-3} is treated as a number in scientific +notation. Similarly for \texttt{e} or any other letter used as the +exponent marker for the input of scientific numbers. (But only one +character can be so used at a time.) Note that the number \emph{must} +start with a digit: \verb`e-1` for instance does not and will be +treated as an algebraic expression involving the exponential constant +(unless \verb`e` is assigned a different value in the vv-list). +\begin{centred} +\verb`$ \eval[^=e]{ x+e-1 }[x=2e-1] $` $\Longrightarrow$ $ \eval[^=e]{ x+e-1 }[x=2e-1] $. +\end{centred} +The problem here is that \verb`2e-1` is treated as a number in scientific +notation but displays in the vv-list as if it were an algebraic expression. +The solution is to put \verb`2e-1` into an \verb`\mbox` or \verb`\text` +command in the vv-list: +\begin{centred} +\verb`$ \eval[^=e]{ x+e-1 }[x=\text{2e-1}] $` $\Longrightarrow$ +$ \eval[^=e]{ x+e-1 }[x=\text{2e-1}] $. +\end{centred} +If you use a particular character as the exponent marker for inputting +numbers in scientific notation, it is good practice \emph{not} to +use that character as a variable, not because it will cause an error +but because it makes expressions harder to read. + +\subsection{Multi-token variables} + +\label{subsec:settingsMultitokSwitch}Variables need not consist of +a single character or token (like $x$ or $\alpha$). Multi-token +symbols like $x'$ or $t_{i}$ or $var$ are perfectly acceptable. +For its internal operations, \texttt{numerica} converts such multi-token +names to single tokens (as discussed in §\ref{subsec:evalVariableNames}). +This conversion takes time. Even if there are no multi-token variables +used at all, \texttt{numerica} still needs to check that that is so. +There is a setting that allows a user to turn off or turn on the check +for such variables by entering +\begin{lyxcode} +xx~=~<integer> +\end{lyxcode} +into the settings option. If \texttt{<integer>} is \texttt{0}, the +check for (and conversion of) multi-token variables is turned off; +if \texttt{<integer>} is \texttt{1} (or any other\emph{ non-zero} +integer), the check, and conversion if needed, goes ahead. By default, +checking for multi-token variables and converting them if found is +turned \emph{on}. (The name for the key, \texttt{xx}, is chosen because +\texttt{x} is the most familiar variable of all, introduced in elementary +algebra, and doubling it like this suggests multi-token-ness.) + +If checking is turned off when a multi-token variable is present, +an error results. We don't need to enter \texttt{xx=1} in the first +of the following examples because the check for multi-token variables +is on by default. Explicitly turning it off in the second produces +an error. +\begin{centred} +\verb`\eval{$ x_0^{\,2} $}[x_0=5]` $\Longrightarrow$ \eval{$ x_0^{\,2} $}[x_0=5],\medskip{} +\verb`\eval[xx=0]{$ x_0^{\,2} $}[x_0=5]` $\Longrightarrow$ \eval[xx=0]{$ x_0^{\,2} $}[x_0=5] +\end{centred} + +\subsection{Parsing arguments of trigonometric functions} + +This setting allows a wider range of arguments to trigonometric functions +to be used (think Fourier series) without needing to insert extra +parentheses in order for them to be read correctly by \verb`\eval`; +see §\ref{subsec:parseTrigFns}. + +\subsection{Using degrees rather than radians} + +\label{subsec:settingsDegrees}You may find it more convenient to +use degrees rather than radians with trigonometric functions.This +can be switched on simply by entering a lowercase \texttt{o} in the +settings option. (The author's fond hope is that the charitable eye +might see a degree symbol in the \texttt{o}.) Thus +\begin{centred} +\verb`\eval[o]{$ \sin 30 $}` $\Longrightarrow$ \eval[o]{$ \sin 30 $}, + +\verb`\eval[o]{$ \arcsin 0.5 $}` $\Longrightarrow$ \eval[o]{$ \arcsin 0.5 $}. +\end{centred} + +\subsection{Specifying a logarithm base} + +\label{subsec:settingsLogBase}If you wish to use \verb`\log` without +a subscripted base in a particular calculation, then add an entry +like +\begin{lyxcode} +log~=~<positive~number${}\,\mathtt{\ne1}$> +\end{lyxcode} +to the settings option of the \verb`\eval` command. The \verb`<positive number>` +does not need to be an integer. It could be \verb`e` (if you object +to writing \verb`\ln`) but is more likely to be $2$ or another small +integer; $10$ is the default. If you want to use this changed base +not for one but most calculations, then add an entry with your choice +of base to a configuration file; see §\ref{sec:settingsDefaults}. + +\subsection{Calculation mode} + +\label{subsec:settingsRecalcMode}A variable may change in the course +of a calculation. This is certainly true of sums and products. If +a parameter in the vv-list depends on the variable then that parameter +will need to be recalculated, perhaps repeatedly, in the course of +a calculation. By entering \label{subsec:settingsCalculationMode} +\begin{lyxcode} +vvmode~=~<integer> +\end{lyxcode} +in the settings option it is possible to turn on or off the ability +to repeatedly evaluate the vv-list; \verb`<integer>` here takes two +possible values, \texttt{0} or \texttt{1}. \texttt{vvmode=0} means +the vv-list is evaluated once at the start of the calculation; \texttt{vvmode=1} +means the vv-list is recalculated every time the relevant variable +changes. + +For example, it may be desirable to place the summand, or some part +of it, in the vv-list. Since the summation variable obviously changes +during the course of the calculation, we need to enter \texttt{vvmode=1} +in the settings option. Repeating an earlier sum (the seting \verb`p=.` +is discussed in §\ref{subsec:settingsPunctuation}) \medskip{} +\begin{verbatim} + \eval[p=.,vvmode=1]{\[ \sum_{k=1}^N f(k) \]} + [N=100,f(k)=1/k^3,{k}=1][4] +\end{verbatim} +$\Longrightarrow$ \eval[p=.,vvmode=1]{\[ \sum_{k=1}^N f(k) \]} + [N=100,f(k)=1/k^3,{k}=1][4] + +As you can see, the summand \texttt{f(k)} has been given explicit +form in the vv-list – equated to \texttt{1/k\textasciicircum 3}. +That means we need to give a preceding value to \texttt{k} in the +vv-list; hence the rightmost entry. But we don't want \texttt{k=1} +appearing in the final display, so we wrap \texttt{k} in braces (see +§\ref{subsec:evalVvSuppressVars}). Since the value \texttt{k=1} applies +only to the first term in the sum, to ensure it is not used for all +terms, we enter \texttt{vvmode=1} in the settings option. This turns +vv-recalculation mode on and ensures \texttt{k=1} is overwritten by +\texttt{k=2}, \texttt{k=3} and so on, and the vv-list recalculated +each time. The final result is the same as before, although recalculating +the vv-list at each step is a more resource-hungry process. The difference +may not be marked for this example; with more complicated expressions +it noticeably takes longer. + +Because it is necessary to activate this switch when using \emph{implicit} +notations – like $f(k)$ in the example – rather than the explicit +form of the function in the main argumet it seems natural to call +\texttt{vvmode=1} \emph{implicit }mode and \texttt{vvmode=0} (the +default) \emph{explicit }mode. Most calculations are explicit mode +– the vv-list is evaluated only once.\emph{ } + +\subsection{Changing the vv-list display format} + +\label{subsec:settingsVvDisplayChangeLocal}In previous formulas with +variables the vv-list has been displayed following the result. It +is wrapped in parentheses following a comma followed by a space. These +formatting elements – comma, space, parentheses – can all be changed +with the settings option. + +The default format specification is +\begin{lyxcode} +\{,\}\textbackslash mskip~12mu~plus~6mu~minus~9mu(vv) +\end{lyxcode} +for a text-style display (an inline formula) and +\begin{lyxcode} +\{,\}\textbackslash mskip~36mu~minus~24mu(vv) +\end{lyxcode} +in a display-style context. The commas are wrapped in braces because +these are items in a comma-separated list. Both entries exhibit the +elements: punctuation (comma), preceding a variable space, preceding +the parenthesized vv-list (the \texttt{vv} placeholder). No full stop +is inserted after the closing parentheses because the \texttt{\textbackslash eval} +command may occur in the middle of a sentence (even in display style). +For inline use, the elasticity of the space becomes relevant when +\TeX{} is adjusting individual lines to fit sentences into paragraphs +and paragraphs into pages. The largest spacing that can be stretched +to is a quad, $18$~mu (mu~=~math unit), and the smallest that +can be shrunk to is a thin space, $3$~mu. In display style,\texttt{ +}the largest spacing specified is the double quad, in line with the +recommendation in \emph{The \TeX{} Book}, Chapter~18, but this can +shrink to a single quad, for instance if the vv-list is heavily populated +with variables so that the evaluated result is pushed well to the +left by the vv-list. (But see below, §\ref{subsec:settings New-line-display}.) + +If you want to change these defaults, enter in the settings option +\begin{lyxcode} +vvi~=~<new~specification> +\end{lyxcode} +to change the inline display and +\begin{lyxcode} +vvd~=~<new~specification> +\end{lyxcode} +to change the display-style display For example the settings +\begin{lyxcode} +vvi~=~\{,\}\textbackslash quad(vv) + +vvd~=~\{,\}\textbackslash qquad(vv) +\end{lyxcode} +would give a comma (in braces since the settings option is a comma-separated +list) and a fixed space (of one or two quads) between the result and +the parenthesized vv-list. + +The vv-list itself in the display specification is represented by +the placeholder \texttt{vv}. If the \texttt{vv} is omitted from the +specification, then the vv-list will not appear at all: +\begin{centred} +\verb`\eval[vvi=?!]{$ \pi $}[\pi=3]` $\Longrightarrow$ \eval[vvi=?!]{$ \pi $}[\pi=3] +\end{centred} +More relevantly, it may well be the case that all variables in the +vv-list are suppressed (wrapped in braces). In that case the display +would look something like \verb`, ()`. To prevent this enter \verb`vvi=` +in the vv-list, in the inline case, or \verb`vvd=` in the display-style +case, i.e. enter an empty value. (Alternatively, use the star option +of the \verb`\eval` command.) + +Another minor wrinkle occurs if you want to change parentheses around +the vv-list to square brackets. Because the settings option is a square-bracket +delimited argument, the square brackets in the specification will, +like commas, need to be hidden in braces, although you can get away +with braces around the whole spec.: +\begin{lyxcode} +vvi=\{,\textbackslash mskip~12mu~plus~6mu~minus~9mu~{[}vv{]}\} +\end{lyxcode} + +\subsection{Displaying the vv-list on a new line } + +\label{subsec:settings New-line-display}Display of a long formula +with many variables, hence a full vv-list, may not fit comfortably +on a line. In an earlier example I used Brahmagupta's formula to calculate +the area of a triangle. It squeezed onto a line. I shall now use his +formula for the area of a cyclic quadrilateral: +\[ +A=\sqrt{(s-a)(s-b)(s-c)(s-d)}. +\] +The extra side (quadrilateral as against triangle) means there is +a further variable to accommodate, not only in the formula but also +in the vv-list. In the following example, the cyclic quadrilateral +is formed by a 45-45-90 triangle of hypotenuse 2 joined along the +hypotenuse to a 30-60-90 triangle. The sides are therefore $\surd2,\surd2,\surd3,1$. +Adding the areas of the two triangles, the area of the quadrilateral +is $A=1+\tfrac{1}{2}\surd3$, or in decimal form, \verb`$\eval{1+\tfrac12\surd3}$` +$\Longrightarrow$ $\eval{1+\tfrac12\surd3}$. Let's check with Brahmagupta's +formula: +\begin{verbatim} + \eval[p=.,vvd={,}\\(vv),*] + {\[ \sqrt{(s-a)(s-b)(s-c)(s-d)} \]} + [s=\tfrac12(a+b+c+d), + a=\surd2,b=\surd2,c=\surd3,d=1] +\end{verbatim} +$\Longrightarrow$ \eval[p=.,vvd={,}\\(vv),*] + {\[ \sqrt{(s-a)(s-b)(s-c)(s-d)} \]} + [s=\tfrac12(a+b+c+d), + a=\surd2,b=\surd2,c=\surd3,d=1] + +\noindent The values agree. The point to note here is the\texttt{ +vvd=\{,\}\textbackslash\textbackslash (vv)} and the \texttt{{*}} +in the settings option. The \texttt{\textbackslash\textbackslash} +in a specification for \texttt{vvd} acts as a trigger for \texttt{numerica} +to replace whatever math delimiters are enclosed by the \verb`\eval` +command with a \verb`multline` environment. As you can see, the specification +inserts a comma after the formula and places the parenthesized vv-list +on a new line. The star \texttt{{*}} if present suppresses equation +numbering by turning the \verb`multline` into a \verb`multline*` +environment. + +Things to note in the use of\texttt{ \textbackslash\textbackslash} +in a \texttt{vvd} specification are that +\begin{itemize} +\item it applies only to the \texttt{vvd} specification, not the \texttt{vvi} +spec.; +\item it applies only when\emph{ }\verb`\eval`\emph{ wraps around }a math +environment of some kind; +\item it has no effect when the \verb`\eval` command is used \emph{within} +a math environment when the presentation of the result is of the form +\emph{result, vv-list}. The formula is not displayed and so the pressure +on space is less and the `ordinary' vv-list specification is used. +\end{itemize} + +\subsection{Punctuation} + +\label{subsec:settingsPunctuation}The \verb`\eval` command can be +used within mathematical delimiters or it can be wrapped around mathematical +delimiters. The latter gives a \emph{formula=result} style of display +automatically, which is convenient. One doesn't need to write the +\emph{formula=} part of the expression, but it causes a problem when +\verb`\eval` wraps around a display-style or similar environment: +how to display a following punctuation mark? For an inline display +we can simply follow the \verb`\eval` command with the appropriate +punctuation, for instance: \verb`\eval{$ 1+1 $}.` $\Longrightarrow$ +\eval{$ 1+1 $}. But with \verb`\[ \]` delimiters used \emph{within} +the \verb`\eval` command – \verb`\eval{\[ 1+1 \]}.` – the fullstop +slides off to the start of the next line, since it is beyond the closing +delimiter. We want it to display as if it were the last element \emph{before} +the closing delimiter. + +Explicitly putting it there – \verb`\eval{\[ 1+1. \]}` – means the +punctuation mark becomes part of the formula. Potentially \texttt{numerica} +then needs to check not just for a fullstop but also other possible +punctuation marks like comma, semicolon, perhaps even exclamation +and question marks. All these marks have roles in mathematics or \texttt{l3fp}. +Including them in the formula means distinguishing their punctuation +role from their mathematical role and can only cause difficulties +(and code bloat). + +Instead, \texttt{numerica} uses the setting +\begin{lyxcode} +p~=~<char(s)>~ +\end{lyxcode} +to place the \texttt{char(s)} after the result but within the environment +delimiters. The default punctuation mark is the comma so that simply +entering \texttt{p} will produce a comma in the appropriate place. +This saves having to write \texttt{p=\{,\}} as would otherwise be +required, since the settings option is a \emph{comma}-separated list. + +Nor is one limited to a single punctuation mark: +\begin{centred} +\verb`\eval[p=\ (but no 8!)]{\[ \frac{1}{81} \]}[9]` $\Longrightarrow$ +\eval[p=\ \text{(but no 8!)}]{\[ \frac{1}{81} \]}[9] +\end{centred} + +\section{Infinite sums and products} + +\label{sec:settingsInfiniteSumsProds}There are ways of tweaking various +default settings to nudge infinite sums and products to a correct +limit. These tweaks are applied via the settings option of the \verb`\eval` +command. + +\begin{table} +\centering +\noindent \centering{}\caption{Settings for infinite sums \& products}\label{tab:settingsSumsProducts} +\noindent \begin{center} +{\small{}% +\begin{tabular}{ll>{\raggedright}p{4cm}l} +\toprule +key & type & meaning & default\tabularnewline +\midrule +\texttt{S+} & int & extra rounding for stopping criterion & \texttt{2}\tabularnewline +\texttt{S?} & $\text{int}\ge0$ & stopping criterion query terms for sums & \texttt{0}\tabularnewline +\texttt{P+} & int & extra rounding for stopping criterion & \texttt{2}\tabularnewline +\texttt{P?} & $\text{int}\ge0$ & stopping criterion query terms for products & \texttt{0}\tabularnewline +\bottomrule +\end{tabular}} +\par\end{center} +\end{table} +The normal convergence criterion used by \texttt{numerica} to determine +when to stop adding/multiplying terms in an infinite sum/product is +\emph{when the next term added/multiplied leaves the total unaltered +when rounded to 2 more digits than the specified rounding value.} +Suppose $T_{k}$ is the sum/product after the inclusion of $k$ terms, +and $r$ is the rounding value. Denote $T_{k}$ rounded to $r$ figures +by $\left(T_{k}\right)_{r}$. \emph{The infinite sum or product stops +at the $(k+1)$-th term (and the value is attained at the $k$-th +term) when }$\left(T_{k+1}\right)_{r+2}=\left(T_{k}\right)_{r+2}$. +The hope is that if this is true at rounding value $r+2$ then at +rounding value $r$ the series or product will have attained a stable +value at that level of rounding. + +For a series of monotonic terms converging quickly to a limit, this +stopping criterion works well, less so if convergence is slower, as +seen earlier with the infinite product for $\sinh1$. The criterion +can fail completely when terms behave in a non-monotonic manner. Distant +terms of a Fourier series, for example, may take zero values; the +criterion is necessarily satisfied but the series may still be far +from its limit. In a product the equivalent would be a distant term +taking unit value. Such series or products may also have initial `irregular' +terms including zero/unit terms. A summation/product might stop after +only one or two additions/multiplications if the criterion were applied +to them. + +To cope with these possibilities, \texttt{numerica} offers two settings +for sums, two for products, summarized in Table~\ref{tab:settingsSumsProducts}. +These are entered in the settings option of the \verb`\eval` command. +\begin{itemize} +\item \texttt{S+=<integer> }or \texttt{P+=<integer>} additional rounding +on top of the specified (or default) rounding for the calculation; +default = $2$ +\begin{itemize} +\item the larger the additional \texttt{<integer>} is, the more likely that +sum or product has attained a stable value at the specified rounding +$r$ +\end{itemize} +\item \texttt{S?=<integer${}\,\mathtt{\ge0}$> }or \texttt{P?=<integer${}\,\mathtt{\ge0}$>} +the number of final terms to query after the stopping criterion has +been achieved to confirm that it is not an `accident' of particular +values; default = $0$ +\begin{itemize} +\item a final few terms to be summed/multiplied and the rounded result after +each such operation to be compared with the rounded result at the +time the stopping criterion was achieved. Suppose the additional rounding +(\texttt{S+} or \texttt{P+}) is $n$ on top of the specified rounding +$r$ and let the number of final checking terms be $m$. Suppose $T_{k_{0}}$ +is the first term at which the stopping criterion is achieved: $\left(T_{k_{0}}\right)_{r+n}=\left(T_{k_{0}+1}\right)_{r+n}$. +What we require of the final query terms is that $\left(T_{k_{0}}\right)_{r+n}=\left(T_{k_{0}+1+j}\right)_{r+n}$ +for $j=0,1,\ldots,m$. +\end{itemize} +\end{itemize} +Previously we found that the infinite product for $\sinh1$ with the +default settings gave the wrong value, $0.174$, deficient by $1$ +in the last digit. We now have the means to tweak the stopping criterion +by increasing the additional rounding: +\begin{verbatim} + \eval[p,P+=3]{\[ + \prod_{k=1}^{\infty} + \biggl(\frac{x^2}{k^2\pi^2} +1\biggr) + \]}[x=1][3] \nmcInfo{prod}. +\end{verbatim} +\noindent $\Longrightarrow$ \noindent \eval[p,P+=3]{\[ + \prod_{k=1}^{\infty} + \biggl(\frac{x^2}{k^2\pi^2} +1\biggr) +\]}[x=1][3] \nmcInfo{prod}. + +\noindent To obtain that last item of information (350 factors), I've +anticipated a little and used the command \verb`\nmcInfo` with the +argument \verb`prod`; see Chapter~\ref{sec:info}. The product now +produces the correct three-figure value, but it takes $350$ factors +to do so. + +Knowing how many terms or factors have been needed helps assess how +trustworthy the result from an infinite sum or product is. For example, +for the exponential series, +\begin{verbatim} + \eval[p]{\[ + \sum_{k=0}^\infty \frac1{k!} + \]}[9] \nmcInfo{sum}. +\end{verbatim} +$\Longrightarrow$ \eval[p]{\[\sum_{k=0}^\infty \frac1{k!} \]}[9] \nmcInfo{sum}. + +To $9$ places of decimals, using the default value \texttt{S+=2}, +the exponential series arrives at the right sum after only $15$ terms. +Convergence is rapid. We can trust this result (and it is in fact +the correct nine-figure value). By contrast, if we didn't know the +value of $\sinh1$ beforehand, noting the number of factors required +would make us justly cautious about accepting the result of the infinite +product calculation. + +One way to gain confidence in a result is to choose a possibly unrealistic +rounding value – say, the default $6$ for the infinite product \-\- +then use \emph{negative} values for the extra rounding, \texttt{S+=-5}, +\texttt{S+=-4}, \ldots{} , so that the stopping criterion applies at +rounding values $s$ of $6+(-5)=1$, $6+(-4)=2$, and so on, but the +result is always presented to $6$ decimal places. One can then see +how the $6$-figure results behave relative to the number of terms +it takes to meet the stopping criterion. A little experimenting shows +that for our infinite product for $\sinh1$ the number of factors +$N_{s}$ at a stopping rounding value $s$ increases in geometric +proportion with a scale factor of about $3$: $N_{s+1}/N_{s}\approx3$. +For the exponential series on the other hand $N_{s}=4+s$, the number +of terms increasing in direct proportion to the stopping rounding +value. + +A similar calculation for the sum of inverse fourth powers of the +integers $\zeta(4)=\sum_{n=1}^{\infty}\frac{1}{n^{4}}$, inverse third +powers, $\zeta(3)$, and inverse squares, $\zeta(2)$, using \verb`\nmcInfo` +to find how many terms are required at each stopping rounding value, +shows that at least over the rounding value range $1$ to $8$, for +inverse fourth powers $N_{s+1}/N_{s}\approx1.7$, for inverse third +powers $N_{s+1}/N_{s}\gtrsim2$ and for inverse squares $N_{s+1}/N_{s}\approx3$. +All are geometric rather than arithmetic progressions, but for inverse +fourth powers the scale factor ($\approx1.7$) is sufficiently small +that for these low values of $s$ the number of terms required does +not grow too quickly. It is a standard result (Euler) that the series +sums to $\pi^{4}/90$: \verb`$ \eval{ \pi^4/90 } $` $\Longrightarrow$ +$ \eval{ \pi^4/90 } $ to six places, and indeed, with the default +\texttt{S+=2}, +\begin{centred} +\verb`\eval[p]{\[ \sum_{k=1}^\infty \frac1{k^4} \]}` $\Longrightarrow$ +\eval[p]{\[ \sum_{k=1}^\infty \frac1{k^4} \]} +\end{centred} +there is complete agreement. + +For inverse third powers, the number of terms required to reach the +stopping criterion grows rapidly for rounding values from $7$ onwards +($2^{7}=128$, $2^{8}=256$, \ldots ). This suggests trying for a +five-figure result (with the default setting \texttt{S+=2} the stopping +rounding value is $7$). Doing this gives a result $1.20205$ to five +decimal places. \emph{HMF} Table 23.3 has this quantity tabulated +to $20$ places and shows our result is too small by $1$ in the final +figure. + +For inverse second powers, the number of terms required to reach the +stopping criterion increase even more quickly: $3^{4}=81$, $3^{5}=243$, +and so on. A three figure answer (with the default setting \texttt{S+=2} +the stopping rounding value is $5$) seems the best we can hope for. +Doing the evaluation gives $1.642$ whereas we know that $\zeta(2)=\pi^{2}/6$ +(Euler's famous result), evaluating to $1.645$. Even with \texttt{S+=3}, +the sum is still too small, $1.644$ after 1007 terms. Increasing +the additional rounding to $4$, \texttt{S+=4}, does finally give +the correct three-figure result, $1.645$, but only after summing +$3180$ terms. + +\subsection{Premature ending of infinite sums} + +All the series considered so far have been monotonic. Trigonometric +series will generally not be so, nor even single-signed. + +Trigonometric sums are computationally intensive and so, for the following +example, I have specified a rounding value of 2. The series +\[ +\sum_{n=1}^{\infty}\frac{4}{n^{2}\pi^{2}}(1-\cos n\pi)\cos2\pi nt +\] +is the Fourier series for the triangular wave function /\!\textbackslash\!/\!\textbackslash\!/\!\textbackslash\!/\!\textbackslash{} \ldots{} +of period 1, symmetric about the origin where it takes its maximum +value 1, crossing the axis at $t=0.25$ and descending to its minimum +$-1$ at $t=0.5$, before ascending to a second maximum at $t=1$ +(and so on). In the interval $[0,0.5)$ the series should sum to $1-4t$. +The problem is that the summand $\frac{4}{n^{2}\pi^{2}}(1-\cos n\pi)\cos2\pi nt$ +vanishes both when $n$ is even and when $4nt$ is an odd integer. +If $t=0.1$ then $4nt$ is never an odd integer so the summand vanishes +only for $n$ even, every second term. We expect the result to be +$1-4\times0.1=0.6$. +\begin{verbatim} + \eval[p]{\[ + \sum_{n=1}^{\infty} + \frac{4}{n^{2}\pi^{2}} + (1-\cos n\pi)\cos2\pi nt + \]}[t=0.1][2] \nmcInfo{sum}. +\end{verbatim} +$\Longrightarrow$ \eval[p]{\[ + \sum_{n=1}^{\infty} + \frac{4}{n^{2}\pi^{2}} + (1-\cos n\pi)\cos2\pi nt +\]}[t=0.1][2] \info{sum}. + +\noindent Only one term? Of course – since the second term $n$ is +even; the term vanishes and the stopping criterion is satisfied. The +way around this problem is to query terms \emph{beyond} the one where +the stopping criterion is achieved, i.e., to set \texttt{S?} to a +nonzero value. We try \texttt{S?=1}: +\begin{verbatim} + \eval[p,S?=1]{\[ + \sum_{n=1}^{\infty} + \frac{4}{n^{2}\pi^{2}} + (1-\cos n\pi)\cos2\pi nt + \]}[t=0.1][2] \nmcInfo{sum}. +\end{verbatim} +$\Longrightarrow$ \eval[p,S?=1]{\[ + \sum_{n=1}^{\infty} + \frac{4}{n^{2}\pi^{2}} + (1-\cos n\pi)\cos2\pi nt +\]}[t=0.1][2] \info{sum}. + +Table~\ref{tab:settingsFinite-sums} lists the results of evaluating +the \emph{finite }sums from $n=1$ to $N$ for values of $N$ around +$65$. Since we have specified a rounding value of $2$ for the calculation, +the stopping criterion\emph{ }applies at a rounding value of $2$ +more than that, $4$. Since $N=64$ is even, the summand for the $64$th +term is zero and the sum takes the same value as for $N=63$. The +$65$th term is the query term and the sum differs, so the summation +continues. The $66$th term vanishes, so the stopping criterion is +met. This time for the query term, the $67$th, the sum retains the +same $4$-figure value, and the summation stops. The result was attained +at the $65$th term. + +\begin{wraptable}{o}{0.5\columnwidth}% +\centering{}\vspace{-4ex} +\caption{Finite sums}\label{tab:settingsFinite-sums} +\setlength{\abovetopsep}{1ex}% +\begin{tabular}{cc} +\toprule +$N$ & $\Sigma$\tabularnewline +\midrule +$63$ & $0.6001$\tabularnewline +$64$ & $0.6001$\tabularnewline +$65$ & $0.5999$\tabularnewline +$66$ & $0.5999$\tabularnewline +$67$ & $0.5999$\tabularnewline +\bottomrule +\end{tabular}\end{wraptable}% +Should we be confident in the result? Increase the number of query +terms to $3$ (there is no point in increasing \texttt{S?} to $2$ +because of the vanishing of the even terms), the sum stops after $113$ +terms, with the same $0.6$ result. Indeed, increasing \texttt{S?} +to $5,7,\ldots$ makes no difference. It still takes $113$ terms +to reach the stable two-figure result $0.6$. + +For a final example, consider the error function +\[ +\erf z=\dfrac{2}{\sqrt{\pi}}\int_{0}^{z}e^{-t^{2}}dt +\] +which can also be rendered as an infinite sum (\emph{HMF }7.1.5): +\[ +\erf z=\sum_{n=0}^{\infty}(-1)^{n}\frac{z^{2n+1}}{n!(2n+1)}. +\] +(\verb`\erf` expanding to \verb`erf` has been defined in the preamble +to this document using \verb`\DeclareMathOperator`.) We calculate +this sum for $z=2$ to $10$ places of decimals. Although this is +an alternating series, it is obvious that the summand never vanishes +when $z\ne0$ as here. Hence there seems no need to change the default +value \texttt{S?=0}. +\begin{verbatim} + \eval[p]{\[ + \frac2{\sqrt{\pi}} + \sum_{n=0}^\infty(-1)^n + \frac{z^{2n+1}}{n!(2n+1)} + \]}[z=2][10*] \nmcInfo{sum}. +\end{verbatim} +$\Longrightarrow$ \eval[p]{\[ + \frac2{\sqrt{\pi}} + \sum_{n=0}^\infty(-1)^n + \frac{z^{2n+1}}{n!(2n+1)} +\]}[z=2][10*] \nmcInfo{sum}. + +According to \emph{HMF }Table 7.1, this calculated value of $\erf2$ +is correct to all $10$ places. But beyond $z=2$ errors will begin +to interfere with the result. Note that $26$ terms means $n=26$ +was the last value of $n$ for which the summand was evaluated. (The +sum stops at the $26$th term, $n=25$, but the next term $n=26$ +needs to be calculated for the stopping criterion.) Fortuitously, +$2^{2\times26+1}=2^{53}$ is the greatest power of $2$ that can be +\emph{exactly} rendered to the $16$ significant figures that \texttt{l3fp} +uses. But $n!$ exceeds the $16$-significant figure limit of \texttt{l3fp} +when $n>21$, so despite the 10-figure result, errors have already +begun to occur in the denominator of the summand and accrue in the +sum when $z=2$. For larger $z$ values the errors can only get worse +and at some point will render the calculated value worthless at any +meaningful rounding value. For example, when $z=7$ the sum apparently +`evaluates' to over $929$ whereas we know that +\[ +\erf z<\dfrac{2}{\sqrt{\pi}}\int_{0}^{\infty}e^{-t^{2}}dt=1. +\] + + +\subsection{Double sums or products} + +Sums or products can be iterated. For instance, the exponential function +can be calculated this way: +\begin{centred} +\verb`\eval[p]{\[ \sum_{k=0}^{\infty}\prod_{m=1}^{k}\frac{x}{m} \]}[x=2]` +$\Longrightarrow$ \eval[p]{\[ \sum_{k=0}^{\infty}\prod_{m=1}^{k}\frac{x}{m} \]}[x=2] +\end{centred} +\noindent which is \verb`\eval{$ e^2 $}` $\Longrightarrow\eval{\ensuremath{e^{2}}}$. + +A second example is afforded by Euler's transformation of series (\emph{HMF} +3.6.27). To calculate $e^{-1}$ we use +\begin{verbatim} + \eval[p={,}\quad \mbox{\nmcInfo{sum}}.] + {\[ \sum_{n=0}^{\infty}\frac{(-1)^{n}}{n!} \]}[3] +\end{verbatim} +$\Longrightarrow$ \eval[p={,}\quad \mbox{\nmcInfo{sum}}.]{\[ \sum_{n=0}^{\infty}\frac{(-1)^{n}}{n!} \]}[3] + +(Note the placement of the information command as the value of the +punctuation key. This keeps it \emph{within }the \texttt{\textbackslash{[} +\textbackslash{]}} delimiters.) Following Euler, this series can +be transformed to the form +\begin{verbatim} + \eval[p,S?=1]{\[ + \sum_{k=0}^\infty \frac{(-1)^k}{2^{k+1}} + \sum_{n=0}^k(-1)^n\binom kn \frac1{(k-n)!} + \]}[3] \nmcInfo{sum}. +\end{verbatim} +$\Longrightarrow$ \eval[p,S?=1]{\[ \sum_{k=0}^\infty \frac{(-1)^k}{2^{k+1}}\sum_{n=0}^k(-1)^n\binom kn \frac1{(k-n)!} \]}[3] \nmcInfo{sum}. + +\noindent Note the setting \verb`S?=1`. Without it, the summation +stops after $1$ term, the $k=0$ term, because the $k=1$ term vanishes. +With \verb`S?=1` it takes $16$ terms of the \emph{outer }sum to +reach the stopping criterion. Since that sum starts at $0$, that +means that changing the upper limit from $\infty$ to $15$ should +give the same result – which it does – but it takes $\tfrac{1}{2}\times16\times17=136$ +terms in total to get there, to be compared with the $9$ terms of +the earlier simpler sum, and the terms are more complicated. Obviously +such double sums are computationally intensive. + +\section{Changing default values} + +\label{sec:settingsDefaults}The settings option enables various settings +to be changed for an individual calculation. You may find yourself +wanting to make such changes sufficiently often that a change of default +value is a better plan than encumbering each calculation with a list +of settings. + +\begin{table}[h] +\centering +\noindent \centering{}\caption{Default values, \texttt{\textbackslash eval} command}\label{tab:settingsDefaults} +\noindent \begin{center} +\begin{tabular}{ll} +\toprule +{\small key} & {\small value}\tabularnewline +\midrule +{\small rounding} & {\small\texttt{6}}\tabularnewline +{\small pad} & {\small\texttt{0}}\tabularnewline +{\small output-sci-notation } & {\small\texttt{0}}\tabularnewline +{\small output-exponent-char} & {\small\texttt{e}}\tabularnewline +{\small\%} & \tabularnewline +{\small input-sci-notation } & {\small\texttt{0}}\tabularnewline +{\small input-exponent-char} & {\small\texttt{e}}\tabularnewline +{\small multitoken-variables } & {\small\texttt{1}}\tabularnewline +logarithm-base & {\small\texttt{10}}\tabularnewline +{\small vv-display} & {\small\texttt{\{,\}\textbackslash mskip 36mu minus 24mu(vv)}}\tabularnewline +{\small vv-inline} & {\small\texttt{\{,\}\textbackslash mskip 12mu plus 6mu minus 9mu(vv)}}\tabularnewline +{\small\%} & \tabularnewline +{\small intify-rounding} & {\small\texttt{14}}\tabularnewline +\% & \tabularnewline +{\small sum-extra-rounding} & {\small\texttt{2}}\tabularnewline +{\small sum-query-terms} & {\small\texttt{0}}\tabularnewline +{\small prod-extra-rounding} & {\small\texttt{2}}\tabularnewline +{\small prod-query-terms} & {\small\texttt{0}}\tabularnewline +\bottomrule +\end{tabular} +\par\end{center} +\end{table} +The way to do that is to create a \emph{configuration file }with the +name \texttt{numerica.cfg} in a text editor. Its entries, one per +line, are of the form \emph{key=value} followed by a comma, and for +clarity preferably one entry per line (although this is not essential).The +key names are noticeably more verbose than the corresponding keys +of the settings option.\emph{ }The possible keys are listed in Table~\ref{tab:settingsDefaults}, +together with their current default values. + +Keys taking one of two possible values, \verb`0` (for \verb`false/off`) +or \verb`1` (for \verb`true/on`), are \verb`pad` (the result with +zeros), \verb`output-sci-notation`, \verb`input-sci-notation`, and +(check for) \verb`multitoken-variables`. + +The table is divided into four parts. +\begin{itemize} +\item The top four rows concern elements that can be changed for individual +calculations with the trailing optional argument of \verb`\eval`: +rounding, padding with zeros, and outputting in scientific notation; +see §\ref{subsec:evalRoundingEtc}. +\begin{itemize} +\item Note that to output the result always in scientific notation requires +two settings, first setting \texttt{output-sci-notation} to \texttt{1}, +and then choosing a character to act as the exponent marker. Because +\texttt{l3fp} uses \texttt{e} for this character, \texttt{numerica} +has made \texttt{e} its default. But this option is turned off by +default (hence the \texttt{0} against this key). +\end{itemize} +\item The next block of rows concern general elements that can be changed +for individual calculations with the settings option of \verb`\eval`; +see §\ref{sec:settingsOption}. Obviously the key names are more expansive +in the present context but the effect is the same. +\begin{itemize} +\item But note that to input numbers in scientific notation requires two +settings, first setting \texttt{input-sci-notation} to \texttt{1}, +and then choosing a character to act as the exponent marker. Because +\texttt{l3fp} uses \texttt{e} for this character, \texttt{numerica} +has made \texttt{e} its default. The option is turned off by default +(hence the \texttt{0} against this key). +\end{itemize} +\item The third block is a single row specifying at what rounding value +a floating point should be considered an integer; see §\ref{subsec:defaultsIntifyingRounding} +below. +\item The last four rows concern default settings for infinite sums and +products. These correspond to the keys \texttt{S+}, \texttt{S?} and +\texttt{P+}, \texttt{P?} of the settings option that can be used to +tweak the behaviour of the stopping criterion for such sums or products; +see §\ref{sec:settingsInfiniteSumsProds}. +\end{itemize} +If you are dissatisfied with any of the default values listed, then +in a text editor create a new file called \texttt{numerica.cfg} and +assign \emph{your} values to the relevant keys. For instance, if you +find yourself working to $4$ figures, that rounding to $6$ is too +many, then make the entry \texttt{rounding=}4. If also you want results +always presented in proper scientific notation,\emph{ $d.d_{1}d_{2}d_{3}d_{4}\times10^{n}$}, +then add a comma after \texttt{4} and enter on a new line (recommended +but not strictly necessary; the comma is the crucial thing), \texttt{output-sci-notation=1,} +(note the comma) and on another new line, \texttt{output-exponent-char=x}. + +Perhaps you also want a non-zero setting for the final query terms +for infinite sums and products. This makes sense if you are largely +dealing with non-monotonic series – like Fourier series. Even the +Euler transformation of the exponential series for $e^{-1}$ discussed +above required a non-zero \texttt{S?}. If you wish to make this change +then add a comma and on a new line add (for instance) \texttt{sum-query-terms += 1,} and again on a new line, \texttt{prod-query-terms = }1. If this +is all you wish to change, then no comma is necessary after this final +entry. Your newly created file should look something like +\begin{lyxcode} +rounding~~~~~~~~~~~~~=~4, + +output-sci-notation~~=~1, + +output-exponent-char~=~x, + +sum-query-terms~~~~~~=~1, + +prod-query-terms~~~~~=~1 +\end{lyxcode} +The white spacing may be different; white space is ignored by \texttt{numerica} +when reading the file. Using it to align the equals signs helps \emph{us} +read the file. Note that the last entry, because it is the last entry, +lacks a comma. Now save the file with the name \texttt{numerica.cfg}. +This file will be read by \texttt{numerica} near the end of its loading +process. These settings will be \texttt{numerica}'s defaults for the +relevant keys. + +\subsection{Location of \texttt{numerica.cfg}} + +Save, yes, but where to? If the new settings are likely to apply only +to your current document, then the document's directory is a sensible +place to put it and \texttt{numerica} will certainly find it there +since it is part of \LaTeX 3 file handling that file searches are +not limited to the \TeX{} distribution (including your personal texmf +tree) but also include the current document directory. But what happens +when you start working on another document? Will you remember to copy +\texttt{numerica.cfg} to its new location? That is why your \emph{personal +texmf tree} is a better place. + +\subsubsection{Personal texmf tree? } + +This is a directory for `waifs and strays' of the \TeX{} system that +are not included in the standard distributions like MiK\TeX{} or \TeX Live. +Here you place personal packages designed for your own particular +circumstances. These may include your own \TeX{} or \LaTeX{} package, +say \texttt{mypackage.sty}, achieving some small or singular effect +that doesn't warrant wider distribution on CTAN. Here you might place +configuration files for other packages with your preferences (unless +the package requires some specific location). Here you can put your +personal bibliography files. + +Your personal texmf tree is structured like the standard MiK\TeX{} +or \TeX Live hierarchy but placed in another location so that there +is no chance of its being overwritten when packages in MiK\TeX{} or +\TeX Live are updated. But these distributions need to be alerted +to its existence. + +For example, in the MiK\TeX{} console, click on \textsf{Settings}, +and then on the \textsf{Directories} tab of the resulting dialog. +Here you get to add your personal texmf hierarchy to the list of paths +that MiK\TeX{} searches, by clicking on the \textsf{+} button, browsing +to your texmf folder and selecting it. By using the up and down arrow +keys that the MiK\TeX{} console provides, ensure that it lies \emph{above +}the the entry for the main MiK\TeX{} tree. That way, files in your +personal texmf tree will be found first and loaded. Now go to the +\textsf{Tasks} menu and click on \textsf{Refresh the filename database}. +This will let MiK\TeX{} know what is held in your personal texmf tree. +Files there can then be used like standard \LaTeX{} packages. + +\subsection{Rounding in \textquoteleft int-ifying\textquoteright{} calculations} + +\label{subsec:defaultsIntifyingRounding}Factorials, binomial coefficients, +summation and product variables, and (in \texttt{numerica}) $n$-th +roots from the \texttt{\textbackslash sqrt} command, all require +integer arguments. These integers may indeed be entered explicitly +as integers, but they can also be determined as the result of a calculation. +Rounding errors may mean the result is not an exact integer. How much +leeway should be allowed before it is clear that the calculation did +not give an integer result? In the default setup, \texttt{numerica} +is generous. A number is considered an integer if it rounds to an +integer when the rounding value is $14$. Since \texttt{l3fp} works +to $16$ significant figures this provides more than enough `elbowroom' +for innocuous rounding errors to be accommodated. If a calculation +does not round to an integer at a rounding value of $14$ then it +seems reasonable to conclude that it has \emph{really }not given an +integer answer, not just that rounding errors have accumulated. If +you want to change this `int-ifying' value for a particular calculation, +then add a line to \texttt{numerica.cfg} like +\begin{lyxcode} +intify-rounding~=~<integer> +\end{lyxcode} +Since \texttt{l3fp} works to $16$ significant figures, values of +\texttt{integer} greater than $16$ are pointless. Generally int-ifying +rounding values will be less than but close to $16$ (although when +testing the code I used some ridiculous values like $3$ or $4$). +If other entries follow this one in the file, then conclude the line +with a comma. + +\section{Parsing mathematical arguments} + +\label{sec:Argument-parsing} A main aim of the \texttt{numerica} +package is to require minimal, preferably no, adjustment to the \LaTeX{} +form in which an expression is typeset in order to evaluate it. But +mathematicians do not follow codified rules of the kind programming +languages insist on when writing formulas – like parenthesizing the +arguments of functions, or inserting explicit multiplication signs +({*}) between juxtaposed terms. Hence the question of where the arguments +of mathematical functions end is acute. For a few functions \LaTeX{} +delimits the argument: think of \verb`\sqrt`, \verb`\frac`, \verb`\binom`; +also \verb`^`. But for functions like \verb`\sin` or \verb`\tanh` +or \verb`\ln`, unary functions, this is not so. Nor is it for sums +and products, and comparisons. + +Before discussing the parsing rules for different groups of functions, +I discuss the means \texttt{numerica} provides to handle exceptions +to those rules, when one \emph{does} need to make some adjustment +to a formula. + +\subsection{The cleave commands \texttt{\textbackslash q} and \texttt{\textbackslash Q}} + +\label{subsec:parseCleave}The word \emph{cleave} has two opposed +meanings: to adhere or cling to, and to split or sever. \texttt{numerica} +defines two commands, \verb`\q` and \verb`\Q` to achieve these opposite +effects. When a mathematical argument is being parsed, the \verb`\q` +command joins the next token to the argument (\emph{cleaves to}); +the \verb`\Q` command severs the next token from the argument (\emph{cleaves +apart}). Neither command is added to the argument nor leaves a visible +trace in the output. + +Thus, without \verb`\q`, +\begin{centred} +\verb`\eval{$ \sin(n+\tfrac12)(x-t) $}[n=3,x=t+\pi,t=1.234]` $\Longrightarrow$ +\eval{$ \sin(n+\tfrac12)(x-t) $}[n=3,x=t+\pi,t=1.234], +\end{centred} +which is $(\sin\tfrac{7}{2})\times\pi$. With \verb`\q` between the +bracketed factors, +\begin{centred} +\verb`\eval{$ \sin(n+\tfrac12)\q(x-t) $}[n=3,x=t+\pi,t=1.234]` $\Longrightarrow$ +\eval{$ \sin(n+\tfrac12)\q(x-t) $}[n=3,x=t+\pi,t=1.234], +\end{centred} +which is $\sin(\tfrac{7}{2}\pi)$. Similarly, without \verb`\q`, +\begin{centred} +\verb`\eval[p]{\[ \cos\frac{2\pi}{T}n(t+\tfrac12T) \]}[T=2,t=1,n=3]` +$\Longrightarrow$ \eval[p]{\[ \cos\frac{2\pi}{T}n(t+\tfrac12T) \]}[T=2,t=1,n=3] +\end{centred} +which is $(\cos\pi)\times3\times(1+\tfrac{1}{2}\times2)$. With \verb`\q` +used twice, once after the fraction and once before the left parenthesis, +\begin{centred} +\verb`\eval[p]{\[ \cos\frac{2\pi}{T}\q n\q(t+\tfrac12T) \]}[T=2,t=1,n=3]` +$\Longrightarrow$ \eval[p]{\[ \cos\frac{2\pi}{T}\q n\q(t+\tfrac12T) \]}[T=2,t=1,n=3] +\end{centred} +which is $\cos(\pi\times3\times2)$. + +It should be noted that for \emph{trigonometric }functions, because +of their use in Fourier series especially, there is another way of +handling arguments with parentheses (and fractions). This is discussed +in §\ref{subsec:parseTrigFns} below. + +For the \verb`\Q` command which splits an argument we have, without +it, +\begin{centred} +\verb`\eval{$ 1/2e $}` $\Longrightarrow$ \eval{$ 1/2e $}, +\end{centred} +which is the reciprocal of $2e$, whereas with the \verb`\Q` command +inserted before \verb`e`, +\begin{centred} +\verb`\eval{$ 1/2\Q e $}` $\Longrightarrow$ \eval{$ 1/2\Q e $}, +\end{centred} +which is a half of $e$. Of course, the meaning in this example would +be clearer if $1/2$ were parenthesized or presented as a \verb`\tfrac`. + +\subsubsection{Mnemonic} + +As mnemonic, best seen in sans serif for the Latin Modern fonts used +in this document, think of the letter \textsf{q} as a circle \emph{clinging +}to a vertical descender; think of the letter \textsf{Q} as a circle +\emph{cut} by the diagonal stroke. + +\subsection{Parsing groups} + +The arguments of different groups of functions are handled in different +ways. The criterion used for deciding when an argument ends for one +group will not be that used for the others. Table §\ref{subsec:defaultsIntifyingRounding} +lists the different groups that \texttt{numerica} takes account of. +At the top are functions or operations that have the smallest reach +when determining where their arguments end; at the bottom are operations +that have the greatest reach. The denominator of a slash fraction +is treated as a unary function and is assigned to group II. By default +trigonometric functions are treated the same as other unary functions +but there is a setting which enables the direct (rather than inverse) +trigonometric functions to accept a wider range of arguments, as occurs +in Fourier series. Hence they are separated into their own group. + +\begin{wraptable}{o}{0.5\columnwidth}% +\noindent \centering{}\caption{Parsing groups}\label{tab:settingsParsing-groups} +{\ttfamily\noindent \begin{center} +{\ttfamily{}% +\begin{tabular}{ll} +\toprule +{\small\textrm{group}} & {\small\textrm{function/operation}}\tabularnewline +\midrule +{\small\textrm{I}} & {\small\textrm{surd, logical Not}}\tabularnewline +{\small\textrm{II}} & {\small\textrm{unary functions, /}}\tabularnewline +{\small\textrm{III}} & {\small\textrm{direct trig. functions}}\tabularnewline +{\small\textrm{IV}} & {\small\textrm{sums, products}}\tabularnewline +{\small\textrm{V}} & {\small\textrm{comparisons}}\tabularnewline +{\small\textrm{VI}} & {\small\textrm{logical And, logical Or}}\tabularnewline +\bottomrule +\end{tabular}} +\par\end{center}}\end{wraptable}% + A formula is a sequence of tokens and brace groups. All parsing occurs +from the left, \LaTeX{} argument by \LaTeX{} argument, where \emph{argument} +means either a token (an N-type argument in \verb`expl3`-speak) or +a brace group (an n-type argument). To distinguish \LaTeX{} arguments +from mathematical arguments I shall when necessary refer to L-args +and M-args. A mathematical argument may end \emph{at} an L-arg, meaning +immediately before the L-arg, or end \emph{with} the L-arg, meaning +immediately after the L-arg. Ending or not will in general depend +on whether the argument is in \emph{first position} – the position +immediately following a function token like \verb`\sin` or \verb`\log` +– or in \emph{general position} – any later position (although for +trigonometric functions we will also need to consider \emph{second} +and even \emph{third }position). + +For counting position, we need to allow for formatting elements and +multi-token numbers – in both decimal and scientific formats. Formatting +elements do not change the position count. This applies to things +like thin spaces or phantoms (and their arguments) or modifiers like +\verb`\left` or \verb`\biggl`. Multi-token numbers (in decimal or +scientific formats) are treated as single items; they advance the +position count by exactly one. \LaTeX{} functions – like \verb`\frac` +– which take \LaTeX{} arguments again advance the position count only +by one. Mathematically, the fraction is viewed as a single unit. + +I shall refer to a token or a token and its \LaTeX{} arguments – like +\verb`\frac` and its arguments – as an \emph{item}. Similarly, a +(possibly multi-token) number is an item. Also it will help to distinguish +tokens within brackets where both brackets lie to the right of a function +from those that do not. The former I call \emph{clothed}; the latter +are \emph{naked}. Thus the plus sign in $(\sin x+y)$ is naked relative +to the sine (one bracket to the left of the function), but is clothed +in $\sin(x+y)$ (both brackets to the right of the function). + +\subsubsection{Parsing group I} + +The only functions in this category are the surd and logical Not. + +Why distinguish the surd from other unary functions? Surely we all +agree that \verb`\sin2\pi`, displaying as $\sin2\pi$, vanishes? +The argument of the sine extends beyond the $2$ to include the $\pi$. +But \verb`\surd2\pi`, displaying as $\surd2\pi$, is understood to +be the product $\surd2\times\pi$. The argument of the surd ends with +the $2$. The surd binds more tightly to its argument than is true +of unary functions generally. + +For parsing group I +\begin{enumerate} +\item if a left bracket is in first position, the mathematical argument +ends with the matching right bracket; otherwise +\item the argument ends with the item in first position and any L- or M-args +required by that item. +\end{enumerate} +If the factorial sign \verb`!` \emph{preceded} its argument, it too +would belong to this parsing state, for it also binds tightly like +the surd. This means that an expression like $\surd4!$ is intrinsically +ambiguous. Is it the square root of $24$ or the factorial of $2$? +In \texttt{numerica} it produces the (perhaps rather odd) error +\begin{centred} +\verb`\eval{$ \surd 4! $}` $\Longrightarrow$ \eval{$ \surd4! $} +\end{centred} +The surd has seized the argument; there is nothing for the factorial +to operate on. The same error arises if the $4$ is parenthesized, +but parenthesizing like either \verb`(\surd 4)!` or \verb`\surd(4!)` +repairs the situation. Because other unary functions (like the sine +or logarithm) do not bind as tightly, this ambiguity does not arise +for them. + +Exponents cause no problem because taking square roots and raising +to a power are commutative operations – the result is the same whichever +is performed first. +\begin{centred} +\verb`\eval{$ \surd 3^4 $}` $\Longrightarrow$ \eval{$ \surd 3^4 $}. +\end{centred} + +\subsubsection{Parsing group II: unary functions, slash fractions} + +In the default setup this category includes the trigonometric and +hyperbolic functions, their inverses, the various logarithms and the +exponential functions, the signum function \verb`\sgn`, and the slash +fraction \verb`/` where the argument to be determined is its denominator. +Note however that there is a setting switch which enables trigonometric + functions to handle parentheses in arguments more generally; see +§\ref{subsec:parseTrigFns}. +\begin{itemize} +\item In parsing group II we wish to accommodate usages like $\ln z^{n}=n\ln z$ +(\emph{HMF} 4.1.11), or $\gd z=2\arctan e^{z}-\frac{1}{2}\pi$ (\emph{HMF} +4.3.117), defining the Gudermannian. The exponent is included in the +argument. Considering $\ln(1+1/n)^{n}$ exponents must also be part +of parenthesized arguments. +\item An approximation to Stirling's formula for the factorial is often +written $\ln N!\approx N\ln N-N$ (widely used in texts on statistical +mechanics). Hence the factorial sign should also be considered part +of the argument. +\item $\ln xy=\ln x+\ln y$ means the argument must reach over a product +of variables. Identities like $\sin2z=2\sin z\cos z$ mean the argument +also reaches over numbers, and expressions like $\sin\tfrac{1}{2}\pi x$ +(\emph{HMF} 4.3.104) mean that it further reaches over \verb`\tfrac`-s +and constants. +\item Essentially \emph{anything }can be in first position, and without +parentheses; e.g. +\begin{itemize} +\item unary functions: $\ln\ln z$ (\emph{HMF} 4.1.52), $\ln\tan\dfrac{z}{2}$ +(\emph{HMF} 4.3.116), +\item fractions: $\ln\dfrac{z_{1}}{z_{2}}$ (\emph{HMF} 4.1.9), $\arcsin\dfrac{(2ax+b)}{(b^{2}-4ac)^{1/2}}$ +(\emph{HMF} 3.3.36), $\ln\dfrac{\tan z}{z}$ (\emph{HMF} 4.3.73), +\item absolute values: $\ln\abs*{\dfrac{a+x}{a-x}}$ (\emph{HMF} 3.3.25), +\item square roots: $\arctan\sqrt{\dfrac{\nu_{1}}{\nu_{2}}F}$ (\emph{HMF +}26.6.8) +\end{itemize} +\end{itemize} +With these examples in mind, for parsing group II +\begin{enumerate} +\item if a left bracket is in first position, the mathematical argument +ends with the matching right bracket and any attached exponent, or +factorial or double factorial sign; otherwise +\item the mathematical argument includes the item in first position and +any L- or M-args required by that item; +\begin{enumerate} +\item if the item in first position is a number, variable, constant or \verb`\tfrac` +\begin{enumerate} +\item the argument appends the next item if it is a number, variable, constant +or \verb`\tfrac`, and so on recursively; or +\item the argument appends the next item if it is an exponent, or facorial +or double factorial sign, and ends there; otherwise +\item the argument ends. +\end{enumerate} +\item if the item in first position is not a number, variable, constant +or \verb`\tfrac` +\begin{enumerate} +\item the argument appends the next item if it is an exponent, or factorial +or double factorial sign, and ends there; otherwise +\item the argument ends. +\end{enumerate} +\end{enumerate} +\end{enumerate} +An argument may extend over (see 2(a)i) numbers, constants, variables +and \verb`\tfrac`-s: $\sin2\tfrac{p}{q}\pi x$ exhibits all elements. + +Illustrating 1, the exponent is included in the argument but not the +following variable: +\begin{centred} +\verb`\eval{$ \log_{10}(1+2+3+4)^3n $}[n=5]` $\Longrightarrow$ \eval{$ \log_{10}(1+2+3+4)^3n $}[n=5]. +\end{centred} +For the sake of the reader, and as one naturally does in any case +to avoid ambiguity, the formula should be written with the variable +$n$ preceding the logarithm: $n\log_{10}(1+2+3+4)^{3}$. The way +the example is written suggests that the writer wished the $n$ to +be considered part of the argument. If that is the case, an outer +set of parentheses would make intentions clear, but it is possible +to leave the argument as written but insert a \verb`\q` command before +$n$: +\begin{centred} +\verb`\eval{$ \log_{10}(1+2+3+4)^3\q n $}[n=5]` $\Longrightarrow$ +\eval{$ \log_{10}(1+2+3+4)^{3}\q n $}[n=5], +\end{centred} +which is $\log_{10}5000.$ + +Illustrating 2(a)ii, again the exponent is included in the argument +but not the following variable: +\begin{centred} +\verb`\eval{$ \log_{10}m^3n $}[m=10,n=5]` $\Longrightarrow$ \eval{$ \log_{10}m^3n $}[m=10,n=5]. +\end{centred} +Again, for the sake of the reader and as one naturally does to avoid +ambiguity, the variable $n$ should precede the logarithm. If in fact +one wants the $n$ included in the argument of the logarithm, the +\verb`\q` command is again available or, better in this case, the +$n$ can be shifted to precede the $m$, which illustrates 2(a)i: +\begin{centred} +\verb`\eval{$ \log_{10}nm^3 $}[m=10,n=5]` $\Longrightarrow$ \eval{$ \log_{10}nm^3 $}[m=10,n=5]. +\end{centred} +Is \texttt{numerica} being too strict when $nm^{3}$ is included in +the argument of the logarithm, but $m^{3}n$ is not? Any criterion +is going to miss some instances where a different outcome might be +desirable. Where an argument ends is affected by visual appearance. +It is simple and easy to remember if it is understood that anything +that breaks the visual appearance of juxtaposed numbers, variables, +constants and \verb`\tfrac`-s ends the argument. An exponent does +just that. + +Illustrating 2(b)ii, the argument stops with the \verb`\dfrac` and +its arguments and does not extend to the following constant: +\begin{centred} +\verb`\eval{$ \sin\dfrac12\pi $}` $\Longrightarrow$ \eval{$ \sin\dfrac12\pi $}. +\end{centred} +Obviously, someone writing an expression like this intends the $\pi$ +to be part of the argument. In that case, a \verb`\tfrac` should +be used. The \verb`\dfrac` breaks the `visual flow' of an argument. +\begin{description} +\item [{Fractions}]~ + +But why not a plain \verb`\frac`? After all, for an inline expression +it displays in the same way as a \verb`\tfrac`. I considered making +the argument-behaviour of \verb`\frac` the same as \verb`\tfrac` +for text-style contexts, and the same as \verb`\dfrac` for display-style +contexts, but that would have meant the same expression evaluating +to different results depending on the context, text-style or display-style, +which ruled it out. Because \verb`\frac` sometimes displays as \verb`\dfrac`, +it necessarily is treated like \verb`\dfrac` (but see §\ref{subsec:parseTrigFns}, +specifically \texttt{()=2}). +\item [{Slash~fractions}]~ + +It is easy to write ambiguous expressions using the slash $/$ to +indicate fractions or division. How should $\pi/2n$ be interpreted? +With from-the-left evaluation and calculator precedence rules which +give equal precedence to {*} (multiplication) and / (division), this +would be interpreted as $(\pi/2)\times n$, but most people will instinctively +interpret it as $\pi/(2n)$. By placing \verb`/` in parsing group +II, this is what \texttt{numerica} does. + +It treats the right-hand argument of the slash \emph{as if it were +the argument of a named function}. This means that $1/2\sin(\pi/6)$ +is parsed as $(1/2)\sin(\pi/6)$ rather than as $1/(2\sin(\pi/6))$. +It also means that $1/2\exp(1)$ and $1/2e$ give different results, +which is acceptable since (in the author's view) they display differently +and are not instinctively read in the same way. +\end{description} + +\subsubsection{Parsing group III} + +\label{subsec:parseTrigFns}By default trigonometric functions are +set to parsing group II. This accommodates many instances of how arguments +are used with these functions, but Fourier series in particular require +more. For them we need to take account of how \emph{parentheses} are +used in arguments. I find $\tan\tfrac{1}{2}(A+B)$ (\emph{HMF }4.3.148), +$\sec\pi(\tfrac{1}{4}+\tfrac{1}{2}az)$ (\emph{HMF }19.3.3), $\cos(2m+p)z$ +(\emph{HMF }20.2.3), $\sin(2n+1)v$ (\emph{HMF }16.38.1). Looking +through various texts discussing Fourier series it is easy to find +examples like +\[ +\cos\frac{2\pi}{T}nt,\quad\cos\frac{2\pi}{T}n(t+\tfrac{1}{2}T), +\] +and +\[ +\cos(N+\tfrac{1}{2})\frac{2\pi\tau}{T},\quad\sin2\pi\left(\frac{x}{\lambda}-\frac{t}{T}\right). +\] +In the last of these \verb`\left` and \verb`\right` have been used +to enlarge the parentheses. + +All these usages can be accommodated by adjusting a setting in the +settings option (§\ref{sec:settingsOption}) of the \verb`\eval` +command: +\begin{lyxcode} +()~=~integer +\end{lyxcode} +where \texttt{integer} is one of \texttt{0, 1, 2}. For convenience +of statement in what follows call parentheses, square brackets or +braces \emph{brackets}. If preceded by a \verb`\left` or \verb`\right` +or \verb`\biggl` or \verb`\biggr` etc. modifier, call them \emph{Brackets}, +with an uppercase `B'. Modifiers do not contribute to the position +count, so that a left Bracket in first position means the modifier +and left bracket are both considered to be in first position. When +it is immaterial whether it is a bracket or a Bracket I write b/Bracket. +The rules that follow do not prescribe what mathematicians \emph{ought} +to do but are intended to be descriptive of certain patterns of mathematical +practice as discerned in \emph{HMF} and a number of texts (about half +a dozen) on Fourier series. +\begin{description} +\item [{\texttt{()=0}}] is the \emph{default} setting; b/Brackets are included +in the argument only if +\begin{itemize} +\item the left b/Bracket is in first position; +\begin{itemize} +\item if the first item beyond the matching right b/Bracket is an exponent, +or factorial or double factorial sign, it is appended to the argument, +which ends there, otherwise +\item the argument ends with the right b/Bracket. +\end{itemize} +\end{itemize} +\item [{\texttt{()=1}}] includes a b/Bracketed expression in the argument, +provided +\begin{itemize} +\item the left Bracket is in first position; +\begin{itemize} +\item if the first item beyond the matching right Bracket is an exponent, +or factorial or double factorial sign, it is appended to the argument, +which ends there, otherwise +\item the argument ends with the right Bracket. +\end{itemize} +\item or the item in first position is a number, variable, constant or \verb`\tfrac` +and the left bracket is in second position; +\begin{itemize} +\item if the first item beyond the matching right bracket is an exponent, +or factorial or double factorial sign, it is appended to the argument, +which ends there, or +\item if the first item beyond the matching right bracket is a number, variable, +constant, or \verb`\tfrac` it is appended to the argument, and so +on recursively, until +\begin{itemize} +\item an exponent, or factorial or double factorial sign is met, which is +appended to the argument which ends there, or +\item an item is met which is \emph{not} an exponent, or factorial or double +factorial sign, or a number, variable, constant or \verb`\tfrac`, +at which point the argument ends, or +\item the end of the formula is reached. +\end{itemize} +\end{itemize} +\end{itemize} +\item [{\texttt{()=2}}] includes a b/Bracketed expression in the argument +provided +\begin{itemize} +\item the left b/Bracket is in first position, or the item in first position +is a number, variable, constant, \verb`\dfrac`, \verb`\frac` or +\verb`\tfrac` and the left b/Bracket is in second position, or the +items in first and second positions are numbers, variables, constants, +\verb`\dfrac`-s, \verb`\frac`-s or \verb`\tfrac`-s and the left +b/Bracket is in third position; +\begin{itemize} +\item if the first item beyond the matching right b/Bracket is an exponent, +or factorial or double factorial sign, it is appended to the argument, +which ends there, or +\item if the first item beyond the matching right b/Bracket is a number, +variable, constant, \verb`\dfrac`, \verb`\frac` or \verb`\tfrac` +it is appended to the argument, and so on recursively, until +\begin{itemize} +\item an exponent, or factorial or double factorial sign is met, which is +appended to the argument which ends there, or +\item an item is met which is \emph{not} an exponent, or factorial or double +factorial sign, or a number, variable, constant, \verb`\dfrac`, \verb`\frac` +or \verb`\tfrac`, at which point the argument ends, or +\item the end of the formula is reached. +\end{itemize} +\end{itemize} +\end{itemize} +\end{description} +The default setting is \texttt{()=0} which is parsing group II behaviour. + +\texttt{()=1} allows $\tan\tfrac{1}{2}(A+B)$ and $\sec\pi(\tfrac{1}{4}+\tfrac{1}{2}az)$, +and $\cos(2m+p)z$ and $\sin(2n+1)v$, and also items on \emph{both} +sides of the bracketed part like $\sin\tfrac{1}{2}(m+n)\pi$ provided +there is only one item between the function and the left bracket: +\begin{centred} +\verb`\eval[()=1]{$ \sin\tfrac16(m+n)\pi $}[m=1,n=2]`. $\Longrightarrow$ +\eval[()=1]{$ \sin\tfrac16(m+n)\pi $}[m=1,n=2]. +\end{centred} +Note that \texttt{numerica} does not check what is included between +the brackets – it could be anything. However inserting \verb`\left`, +\verb`\right` modifiers before the parentheses restricts the argument +of the sine in this example to the \verb`\tfrac`: +\begin{centred} +\verb`\eval[()=1]{$ \sin\tfrac16\left(m+n\right)\pi $}[m=1,n=2]`. +$\Longrightarrow$ \eval[()=1]{$ \sin\tfrac16\left(m+n\right)\pi $}[m=1,n=2]. +\end{centred} +\texttt{()=2} draws no distinction between brackets and Brackets. +It allows all \texttt{()=1} possibilities but also \emph{two }items +(of a suitable kind) before the left b/Bracket; it also allows \verb`\dfrac`-s +and \verb`\frac`-s in addition to \verb`\tfrac`-s. + +The following examples are taken from different texts on Fourier series. +The first shows a \verb`\frac` being included in the argument, the +second shows \emph{two} items – including a \verb`\frac` – preceding +the left parenthesis, the third shows a \verb`\frac` to the right +of the parentheses, and the fourth shows parentheses using \verb`\left`-\verb`\right` +modifiers with two items preceding them: +\[ +\cos\frac{2\pi}{T}nt,\quad\cos\frac{2\pi}{T}n(t+\tfrac{1}{2}T),\quad\text{\ensuremath{\sin(N+\tfrac{1}{2})\frac{2\pi\tau}{T}}\ensuremath{\quad}and}\quad\sin2\pi\left(\frac{x}{\lambda}-\frac{t}{T}\right). +\] +All these usages are accommodated by the \verb`()=2` setting. For +instance +\begin{verbatim} + \eval[p,()=2] + { + \[ \sin(N+\tfrac12)\frac{2\pi\tau}T \] + }[N=1,\tau=2,T=3] +\end{verbatim} +$\Longrightarrow$ \eval[p,()=2] + { + \[ \sin(N+\tfrac12)\frac{2\pi\tau}T \] + }[N=1,\tau=2,T=3]which is the sine of $(\tfrac{3}{2})\times(\tfrac{4}{3}\pi)=2\pi$ +(and \emph{not }$(\sin\tfrac{3}{2})(\tfrac{4}{3}\pi)$ ), where a +\verb`\frac` trailing the parentheses has been included in the argument. +Or consider +\begin{verbatim} + \eval[p,()=2] + {\[ + \sin2\pi\left(\frac{x}{\lambda} + -\frac{t}{T}\right) + \]}[x=1,\lambda=2,t=3,T=4] +\end{verbatim} +$\Longrightarrow$ \eval[p,()=2] + {\[ + \sin2\pi\left(\frac{x}{\lambda} + -\frac{t}{T}\right) + \]}[x=1,\lambda=2,t=3,T=4] which is the sine of $2\pi\times(-\tfrac{1}{4})=-\tfrac{1}{2}\pi$ +(and \emph{not} $\sin2\pi$ times the parenthesised expression) where +there are two items before the parentheses which surround two \verb`\frac`-s +and \verb`\left` and \verb`\right` modifiers have been used with +the parentheses. + +However a usage like $\sin(n+\tfrac{1}{2})(x-t)$, noted in two different +texts, is not available without explicit use of the \verb`\q` command +between the parenthesized groups. + +\subsubsection{Parsing group IV} + +The only members of this group are \verb`\sum` and \verb`\prod`. + +For parsing group IV +\begin{enumerate} +\item the argument ends +\begin{enumerate} +\item at the first naked plus or minus sign encountered, or +\item at the first comparison sign or comparison command encountered, or +\item at the first logical And or logical Or sign encountered, or +\item at the end of the formula. +\end{enumerate} +\end{enumerate} +In practice this means mainly (a) and (d), and seems to be the instinctive +practice. \emph{HMF} has multiple examples in multiple chapters of +the argument to a sum ending at a naked plus sign: 7.3.12 \& 7.3.14, +9.1.11 \& 9.1.77, 9.6.35 \& 9.6.43, 11.1.9, \ldots{} (at that point +I stopped looking). They were all of the form +\[ +\sum\text{argument}+\ldots +\] + A minus sign serving the same purpose was harder to find but \emph{HMF} +10.4.65 \& 10.4.67 are two instances. I considered whether a \verb`\times` +or slash fraction sign \verb`/` might end the argument of a sum, +but surely we need to allow things like $\sum1/n^{2}$ which rules +out the slash and \emph{HMF} 9.9.11 provides two of a number of instances +in \emph{HMF} of sum arguments continuing past explicit \verb`\times` +signs (at line breaks when a summand spills onto a second line). + +Because they are evaluated using the same code as sums I (unthinkingly) +placed products with sums but doubts later intruded. In \emph{HMF} +products occur only occasionally and are almost all of the form +\[ +\prod\left(\text{argument}\right) +\] +where the argument is bracketed (often with \verb`\left \right` modifiers) +and the multiplicand ends with the right bracket. At least twice (\emph{HMF +}6.1.25 and 24.2.2.1) an exponent ($-1$) is attached to the right +bracket and the argument ends there. Looking further afield, a text +on number theory has examples where the argument of the product extends +to \emph{three} parenthesised factors, $\prod\left(\text{arg}1\right)\left(\text{arg2}\right)\left(\text{arg3}\right)$ +and a number of others where it extends to two. A text on theory of +functions has +\[ +\prod_{n=1}^{\infty}\left(1+\frac{z}{n}\right)e^{z/n} +\] +although \emph{HMF}, for the same expression, encloses the two factors +within (large) square brackets, as if some ambiguity existed as to +how far the reach of the \verb`\prod` extended. + +\emph{Tentatively} I retain products here in the same group as sums. + +\subsubsection{Parsing group V} + +Comparison symbols compose this group: \texttt{=}, \texttt{<}, \texttt{>}, +\verb`\ne`, \verb`\le`, \verb`\ge`, \verb`\leq`, \verb`\geq`, +and the various comparison commands from the \texttt{amssymb} package +listed in §\ref{subsec:evalAmssymb-comparisons}. Because of the way +\texttt{numerica} handles comparisons, it is the argument on the right-hand +side of the relation that needs determining. + +For parsing group V +\begin{enumerate} +\item the argument ends at +\begin{enumerate} +\item the first logical And or logical Or encountered, or +\item the first comparison sign or command encountered, or +\item the end of the formula. +\end{enumerate} +\end{enumerate} + +\subsubsection{Parsing group VI} + +Logical And and logical Or are the sole members of this group. It +is the right-hand side of the And or Or command that needs determining. + +For parsing group VI +\begin{enumerate} +\item the argument ends at +\begin{enumerate} +\item the first logical And or logical Or encountered, or +\item the end of the formula. +\end{enumerate} +\end{enumerate} + +\subsubsection{Disclaimer} + +The parsing rules of the different groups are not normative; they +are not statements of how mathematical formulas should be written. +Rather they are attempts to discern regularities in how mathematicians +often do write formulas. It is how things look in the pdf, not \LaTeX , +that is the guide. You are always free to parenthesize as you see +fit and to insert cleave commands (\verb`\q` or \verb`\Q`) to force +outcomes. + +(But note that parenthesizing has its limits. For sums, writing +\[ +\sum\left(\mathtt{<stuff>}\right)\mathtt{<more-stuff>} +\] + does not necessarily end the summand at the right parenthesis: it +ends at the first naked $+$ or $-$ sign, or \verb`\Q` command, +encountered.) + +The rule should always be to write expressions that are clear to the +reader of the pdf. An expression that is ambiguous to the reader, +even if it fits within the parsing rules, is to be deplored. The \emph{intent} +is that \verb`\eval` can parse unambiguous expressions correctly. + +\chapter{Nesting \texttt{\textbackslash eval} commands} + +\label{chap:Nesting}\verb`\eval` commands can be used within \verb`\eval` +commands, both as part of the formula being evaluated or as part of +the vv-list or both. Only in special circumstances is this likely +to be useful – perhaps when a calculation can be divided into two +or more parts where different settings are appropriate for the different +parts. One can imagine cases in which trigonometric functions are +involved and different \texttt{()} settings would be helpful in different +parts of the formula. Nesting of command within command becomes especially +significant with the additional commands available when \texttt{numerica} +is loaded with the \texttt{plus} or \texttt{tables} options; see the +associated documents \texttt{numerica-plus.pdf} and \texttt{numerica-tables.pdf}. +Since those additional commands are not available in this document, +I restrict myself here to some `toy' examples of \verb`\eval` commands +within \verb`\eval` commands to show how things work. + +\section{Star option for inner \texttt{\textbackslash eval}} + +The \verb`\eval` command `digests' a \LaTeX{} formula to produce +an \verb`l3fp`-readable formula. This is then fed to \verb`l3fp` +to be evaluated. The evaluated output is then formatted in various +ways to be displayed. If the inner \verb`\eval` command produces +formatted output, it is \emph{that} that the outer \verb`\eval` command +will attempt to digest – and fail. Hence \emph{always} use the star +option for the inner \verb`\eval` command. That means the outer \verb`\eval` +is feeding on a number only: +\begin{centred} +\verb`\eval{$ \sin(\eval*{\sin x}[x=\pi/6]\pi) + 1 $}` $\Longrightarrow$ +\eval{$ \sin(\eval*{\sin x}[x=\pi/6]\pi) + 1$}. +\end{centred} +Also no math delimiters are used in the inner command. These are irrelevant +with the star option in any case, but in the present context would +cause error if included because they would be treated as part of the +formula and thereby produce an `unknown token' error message. In +the presentation of the overall result that the inner \verb`\eval` +command is evaluated, showing as $0.5$. + +\section{Nesting in the vv-list} +\begin{centred} +\verb`\eval{$ \sin k\pi + 1 $}[k=\eval*{\sin x},x=\pi/6]` $\Longrightarrow$ +\eval{$ \sin k\pi + 1 $} [k=\eval*{\sin x},x=\pi/6]. +\end{centred} +When the inner \verb`\eval` command is in the vv-list of the outer +command and has a vv-list of its own, then the entire inner command +needs to be placed in braces: +\begin{centred} +\verb`\eval{$ \sin k\pi + z $}[k={\eval*{y\sin x}[x=\pi/4,y=1/\surd2]},z=1]` +$\Longrightarrow$ \eval{$ \sin k\pi + z $} [k={\eval*{y\sin x}[x=\pi/4,y=1/\surd2]},z=1]. +\end{centred} +The vv-list of the inner \verb`\eval` command contains both a comma +and square brackets. Both elements need to be hidden from the outer +\verb`\eval` in order that \emph{its }vv-list be parsed correctly. +Hence braces surround the inner \verb`\eval` and its arguments. The +same need arises if the inner \verb`\eval` has a non-empty settings +option – another comma-separated square-bracketed option. + +The values of variables used in an inner \verb`\eval` command are +restricted to that command; they do not `leak' into the outer calculation. +But variables and their values in the outer vv-list are available +for use in the inner \verb`\eval` command (unless a value is explicitly +changed in the inner vv-list). + +\subsection{Debugging} + +\label{subsec:nestDebugging}It is worth looking at the debug display +when \verb`\eval` commands are nested. For the outer \verb`\eval` +command: +\begin{centred} +\verb`\eval[dbg=210]{$ \sin \eval*{\sin x}[x=\pi/6]\pi + 1 $}` $\Longrightarrow$ +\eval[dbg=210]{$ \sin \eval*{\sin x}[x=\pi/6]\pi + 1 $} +\end{centred} +and when the inner \verb`\eval` is in the vv-list, +\begin{centred} +\verb`\eval[dbg=210]{$ \sin k\pi + 1 $}[k=\eval*{\sin x},x=\pi/6]` +$\Longrightarrow$ \eval[dbg=210]{$ \sin k\pi + 1 $} [k=\eval*{\sin x},x=\pi/6] +\end{centred} +For the inner \verb`\eval` command debugging still works but in an +idiosyncratic way. To clarify exactly what is going on I have added +a \verb`\left( \right)` pair around the entire inner \verb`\eval` +command. Note that I have also used a \emph{negative} \texttt{dbg} +value. With a positive value, the right parenthesis is pressed toward +the right margin of the page. The negative value limits the display +to the text width and gives the much neater result shown. +\begin{verbatim} + \eval[()=2]{$ + \sin\left( + \eval*[dbg=-210]{ \sin x }[x=\pi/6] + \right)\pi + 1 $} +\end{verbatim} +$\Longrightarrow$ \eval[()=2]{$ + \sin\left( + \eval*[dbg=-210]{ \sin x }[x=\pi/6] + \right)\pi + 7 $} + +\medskip{} +The debug display from the inner \verb`\eval` command has been inserted +into the formula of the outer \verb`\eval` in the position occupied +by the inner \verb`\eval`. I did not deliberately code for this, +but have decided to leave it as is, since there can be no confusion +about which \verb`\eval` command is being `debugged', despite the +potential for some rather odd displays. In this last example, in order +to both use \verb`\left(...\right)` and have the calculation give +the previous result I have employed the setting \verb`()=2` in the +outer \verb`\eval`; see §\ref{subsec:parseTrigFns}. + +\chapter{\texttt{\textbackslash nmcInfo (\textbackslash info)}} + +\label{sec:info}Used after the evaluation of an `infinite' process, +the \verb`\nmcInfo` command, or its equivalent short-name form \verb`\info` +will tell you how many terms or factors or iterations or steps were +needed to arrive at the result. The syntax of the \verb`\nmcInfo` +command is +\begin{lyxcode} +\textbackslash nmcInfo\{<arg>\}~ +\end{lyxcode} +where \texttt{<arg>} is restricted to one of two choices at present, +either \texttt{sum} or \texttt{prod}. If the package \texttt{numerica-plus.def} +is loaded (see §\ref{subsec:introPackagesOptions} and the associated +document \texttt{numerica-plus.pdf}) two further arguments are possible: +\texttt{iter} and \texttt{solve}. + +There is a starred form of the command: +\begin{lyxcode} +\textbackslash nmcInfo{*}\{<arg>\} +\end{lyxcode} +(or \verb`\info*{<arg>}`). As with the \verb`\eval` command the +star has the effect of suppressing anything other than the numerical +result from the display. + +As an example, let's test a standard identity, $\cosh^{2}x-\sinh^{2}x=1$, +`the hard way'. We know that $\cosh x=\sum_{n=0}^{\infty}\frac{x^{2n}}{(2n)!}$ +and $\sinh x=x\prod_{k=1}^{\infty}\left(1+\frac{x^{2}}{k^{2}\pi^{2}}\right)$. +The difference of their squares should be $1$: +\begin{verbatim} + \eval{\[ + \left[\sum_{n=0}^{\infty} + \frac{x^{2n}}{(2n)!} + \right]^2- + \left[x\prod_{k=1}^{\infty} + \left(1+\frac{x^{2}}{k^{2}\pi^{2}}\right) + \right]^2 + \]}[x=1][3] \info{sum}\quad \info{prod} +\end{verbatim} +$\Longrightarrow$ \eval{\[ + \left[\sum_{n=0}^{\infty} + \frac{x^{2n}}{(2n)!}\right]^2- + \left[x\prod_{k=1}^{\infty} + \left(1+\frac{x^{2}}{k^{2}\pi^{2}}\right)\right]^2 + \]}[x=1][3] \info{sum}\quad \info{prod}. + +Nearly right. Obviously the product converges only slowly which is +where the error comes from (see the discussion in §\ref{sec:settingsInfiniteSumsProds}, +where we needed the extra rounding setting \texttt{P+=3} and $350$ +factors to get a correct 3-figure value). The point of the example +is to show the information command being used for both sum and product +in the one evaluation. One does not exclude the other. + +The information command can also be placed in the settings option +as the value of the punctuation setting. An example of this has already +been provided earlier which I'll repeat here: +\begin{verbatim} + \eval[p=\mbox{,\quad\nmcInfo{sum}.}] + {\[ \sum_{n=0}^{\infty}\frac{(-1)^{n}}{n!} \]}[3] +\end{verbatim} +$\Longrightarrow$ \eval[p=\mbox{,\quad\nmcInfo{sum}.}]{\[ \sum_{n=0}^{\infty}\frac{(-1)^{n}}{n!} \]}[3] + +Because of the \texttt{\textbackslash{[} \textbackslash{]}} delimiters, +if the information command had been placed \emph{after} the \texttt{\textbackslash eval} +command, it would have slid down to the next line. As it is, it resides +\emph{inside} the \texttt{\textbackslash{[} \textbackslash{]}} +delimiters, on the same line as the expression. This may be significant +for adjusting vertical spacing of subsequent elements of the document. + +\section{Errors} + +Should the wrong argument be used in the \verb`\nmcInfo` command, +no harm is done: +\begin{verbatim} + \eval{$ + \sum_{k=0}^{\infty}\binom \alpha k x^k + $}[x=1/2,\alpha=3], \ \info{prod} +\end{verbatim} +$\Longrightarrow$ \eval{$ \sum_{k=0}^{\infty}\binom \alpha k x^k $}[x=1/2,\alpha=3],\ \info{prod}. + +$119$ \emph{factors}? The information command is remembering a previous +result, the last time \verb`prod` was used as its argument. Changing +the argument from \verb`prod` to \verb`sum` reveals the correct +number of \emph{terms}. + +Should a non-existent argument be used, an error message is generated: +\begin{verbatim} + \eval{$ + \sum_{k=0}^{\infty}\binom \alpha k x^k + $}[x=1/2,\alpha=3], \\ \info{Fred} +\end{verbatim} +$\Longrightarrow$ \eval{$ \sum_{k=0}^{\infty}\binom \alpha k x^k $}[x=1/2,\alpha=3],\\ \info{Fred} + +\chapter{Saving and reusing results } + +\label{chap:Saving-and-retrieving}You may want to use at some place +in a document a result calculated earlier. It would be good to be +able to do so without having to do the calculation again at the new +location. \texttt{numerica} offers a command \verb`\nmcReuse` which +saves a result to a control sequence which can be used elsewhere in +the document, expanding to the saved result. The control sequence +and its content are also saved to file for use on other occasions. + +The syntax of \verb`\nmcReuse` is simple. The command takes two optional +arguments, a star (asterisk) and a conventional square-bracket delimited +argument. If both are used it looks like +\begin{lyxcode} +{\small\textbackslash nmcReuse{*}{[}csname{]}}{\small\par} +\end{lyxcode} +where \texttt{csname} is the proposed name of what will become the +control sequence \verb`\csname` containing the latest result from +the \verb`\eval` command. The name should be composed of letters +only. + +As with \verb`\nmcEvaluate` and \verb`\nmcInfo` there is a short-name +form, \verb`\reuse`, for \verb`\nmcReuse`. If a conflict with another +package arises, it should be possible to fall back on \verb`\nmcReuse`. + +\section{Use without optional argument: \texttt{\textbackslash nmcReuse}} + +Suppose your document is \verb`mydoc.tex` (so that the \LaTeX{} command +{\small\verb`\jobname`} expands to \verb`mydoc`). If \verb`\nmcReuse` +is used without optional arguments, then \texttt{numerica} checks +for the existence of a file \verb`mydoc.nmc` in the current document +directory\texttt{ }and if found loads and records the contents of +\verb`mydoc.nmc`. The contents should be a comma separated list of +control sequences and braced values like \texttt{\textbackslash csname1 +\{value1\},\textbackslash csname2 \{value2\},...} The control sequences +can then be used elsewhere in the document. In particular, control +sequences containing numerical values can be used in expressions within +\verb`\eval` commands and in vv-lists.\footnote{The associated document \texttt{numerica-plus.pdf} describes how other +quantities like tables and sequences of numerical values (iterates, +recurrences) can also be saved and reused.} + +Note that the control sequences are given \LaTeX{} definitions using +\verb`xparse`'s \verb`\NewDocumentCommand` (a little more general +than \LaTeXe 's \verb`\newcommand`) and can be used at any later +point in the document simply by entering the control sequence (e.g., +\verb`\csname1`) there (but see §\ref{subsec:reuseGroup-level}). +Should there already be a control sequence with the same name, \LaTeX{} +will generate an error and halt compilation. + +\section{Use with optional name: \texttt{\textbackslash nmcReuse{[}csname{]}}} + +If a name \emph{is} supplied, say \verb`\nmcReuse[csname]`, then +not only does \texttt{numerica} first look for \verb`mydoc.nmc` (assuming +your document is called \verb`mydoc.tex`) and load the values stored +in that file if they have not already been loaded, but it also defines +\verb`\csname` to contain the latest result from the \verb`\eval` +command. Should \verb`\csname` already be present in \verb`mydoc.nmc` +and so have been loaded with the other values from \verb`mydoc.nmc`, +the old value is overwritten with the new value using \verb`xparse`'s +\verb`\RenewDocumentCommand` and the new value is saved to the file +\verb`mydoc.nmc`. + +\subsection{Group level} + +\label{subsec:reuseGroup-level}Control sequences like \verb`\csname` +defined by \verb`\nmcReuse` are defined within the current group +level. A usage like +\begin{centred} +\verb`$ \eval{1+1}\reuse[two] $` +\end{centred} +confines the definition of \verb`\two` to the environment delimited +by the dollar signs. A usage like +\begin{centred} +\verb`$ \eval{1+1} $ \reuse[two]`, +\end{centred} +where the command has been moved outside the math delimiters, still +confines the definition of \verb`\two` to whatever larger environment +the \verb`\reuse` command might lie within. If in fact the definition +occurs at document level then \verb`\two` (in the present example) +is available for use throughout the document, otherwise it is available +only within the confines of the current environment. + +This is likely to be \emph{not }what is wanted. The remedy is simple: +precede the saved control sequence – \verb`\two` in the present instance +– with a `naked' \verb`\reuse` command. This loads the value stored +in \verb`mydoc.nmc`. In the following example, \verb`\reuse` is +used within a math environment which is followed by some text (\verb`blah blah result:`) +then a `naked' \verb`\reuse` command and the control sequence \verb`\two` +(between math delimiters, which are necessary for reasons explained +in the next section). +\begin{centred} +\verb`$ \eval{1+1} \reuse[two] $, blah blah result: \reuse $\two$.` +$\Longrightarrow$ $ \eval{1+1} \reuse[two]$, blah blah result: \reuse $\two$. +\end{centred} + +\section{What is saved?} + +\label{sec:reuseWhat-is-saved}In the default configuration \verb`\nmcReuse` +saves the entirety of the display resulting from the latest \verb`\eval`-uation. +This may include invisible formatting elements meaning that what one +expects to be only a number cannot be inserted into text without causing +a \LaTeX{} error; it requires a math environment to print – see the +last example. + +The simplest way to avoid this awkwardness is to use \verb`\eval` +with the star option. This produces a numerical result with \emph{no +}formatting. In the following example, I calculate \verb`11+11` with +\verb`\eval*` and store the value in the control sequence \verb`\twos`. +I then enter some text (\verb`Blah blah blah:`) and insert the control +sequence \verb`\twos` into the text without math delimiters. As you +can see, \verb`\twos` has expanded to $22$, the result of the calculation. +\begin{centred} +\verb`\eval*{$ 11+11 $}. \nmcReuse[twos] Blah blah blah: \twos` $\Longrightarrow$ + \eval*{$ 11+11 $}. \nmcReuse[twos] Blah blah blah: \twos +\end{centred} + +\subsection{Viewing what is saved: \textbackslash reuse\texttt{{*}}} + +To view what is saved in the \verb`.nmc` file append a star (asterisk) +to the \verb`\reuse` command. (This makes particular sense when using +\texttt{numerica} in a program like \LyX{} with a preview facility; +see Chapter~\ref{chap:LyX}.) +\begin{centred} +\verb`\reuse*` $\Longrightarrow$ \reuse* +\end{centred} +Particularly notable here is the invisible formatting \verb`\mathchoice{}{}{}{}` +accompanying \verb`2` in the value of \verb`\two`. + +The two options of the\verb`\reuse` command can be used together, +in which case the control sequence resulting from the name supplied +in the square-bracketed option will appear in the list resulting from +the star option, i.e. the list contains not just what has been saved +earlier but also the current control sequence saved. + +\subsection{\texttt{\textbackslash eval}'s \texttt{reuse} setting} + +\label{subsec:reuse=00005Ceval's-reuse-setting}The star option of +the \verb`\eval` command allows a purely numerical result to be saved, +but also only a number is displayed. By using the \verb`reuse` setting +of the \verb`\eval` command it is possible to have both a full display +of an evaluation, vv-list and all, and to save only a numerical result. + +For the \emph{starred} form of the \verb`\eval` command it is always +\emph{only the numerical result} that is saved, whatever the value +of the \texttt{reuse} key in the settings option of the \verb`\eval` +command. + +For the \emph{unstarred} form of the \verb`\eval` command exactly +what is saved with \verb`\nmcReuse` depends on the \texttt{reuse} +setting: +\begin{lyxcode} +reuse~=~<integer> +\end{lyxcode} +where \verb`<integer>` can take one of two values, +\begin{itemize} +\item \texttt{reuse=0} (the default) saves\emph{ the form that is displayed} +including a formatting component. If the result is displayed in the +form \emph{formula=result (vv-list)} then that is what is saved; if +the display is of the form \emph{result (vv-list)} then that is what +is saved; if the vv-list is empty, an empty formatting component is +still present in the saved result; +\item \texttt{reuse=1} (or, indeed, any non-zero integer) saves only the +numerical result with no other elements of the display (meaning no +formatting component). +\end{itemize} +Thus, with the default setting (\texttt{reuse=0}) the full content +of the display is saved: +\begin{centred} +\verb`\eval{$ x + y $}[x=1,y=1] \reuse[iandi]` $\Longrightarrow$ +\eval{$ x + y $}[x=1,y=1] \reuse[iandi]. +\end{centred} +To check that this is the case, \verb`\reuse \iandi` $\Longrightarrow$ +\reuse \iandi . + +On the other hand, with \texttt{reuse=1} only the numerical value +is saved: +\begin{centred} +\verb`\eval[reuse=1]{$ x + y $}[x=1,y=1] \reuse[iandi]` $\Longrightarrow$ +\eval[reuse=1]{$ x + y $}[x=1,y=1] \reuse[iandi], +\end{centred} +which we can check here: \verb`\reuse\iandi` $\Longrightarrow$ \reuse\iandi . + +\subsubsection{\texttt{\textbackslash reuse} in the preamble} + +To gain access from the outset to the control sequences stored in +the file \texttt{mydoc.nmc}, place \verb`\nmcReuse` without an optional +argument in the preamble (but after \verb`\usepackage{numerica}`). + +\chapter{Using \texttt{numerica} with \protect\LyX} + +\label{chap:LyX}The document processor \LyX{} has a facility that +enables snippets from a larger document to be compiled separately +and the results presented to the user without having to compile the +entire document. The present document was written in \LyX . The demonstration +calculations were evaluated using this \emph{instant preview} facility. + +To use \texttt{numerica} in \LyX{} go to \textsf{Document \lyxarrow{} +Settings \lyxarrow{} LaTeX Preamble} and enter +\begin{lyxcode} +\textbackslash usepackage\{numerica\} +\end{lyxcode} +then click \textsf{OK}. However preview poses problems for the straightforward +use of the \verb`\nmcReuse` command. If you wish to use this command +in \LyX{} then \texttt{numerica} should be loaded with the \texttt{lyx} +package option. Thus in \textsf{Document \lyxarrow{} Settings \lyxarrow{} +LaTeX Preamble} enter +\begin{lyxcode} +\textbackslash usepackage{[}lyx{]}\{numerica\} +\end{lyxcode} +then click \textsf{OK}, or you may wish to follow the above line in +the preamble with \verb`\nmcReuse`, +\begin{lyxcode} +\textbackslash usepackage{[}lyx{]}\{numerica\} + +\textbackslash nmcReuse +\end{lyxcode} +and \emph{then} click \textsf{OK}. The additional line ensures all +saved values are available in your document from the outset. + +\section{Instant~preview} + +Preview performs localised mini-\LaTeX{} runs on selected parts of +a document (for instance, the mathematical parts) and displays the +results in \LyX{} while the user continues to work on the surrounding +document.\texttt{ numerica} uses these local \LaTeX{} runs to do its +evaluations and display their results. That means you get feedback +on your calculations almost immediately. + +To use this facility first ensure that instant preview is turned on. +This means selecting \textsf{Tools \lyxarrow Preferences \lyxarrow Look +\& Feel \lyxarrow{} Display} and against \textsf{Instant preview} selecting +\textsf{On}, then clicking \textsf{OK}. + +\subsection{Conflict with hyperref support?} + +There may be a conflict in \LyX{} between hyperref support and preview, +not that the previews do not form but that their formation takes a +circuitous path that noticeably slows their display.\footnote{At least there is on the author's Windows 10 system, but I'm not sure +that this is general.} If this occurs on your system, go to \textsf{Document \lyxarrow{} +Settings \lyxarrow{} PDF Properties} and ensure the check box \textsf{Use +Hyperref Support} is cleared. By all means reset the check box when +you come finally to compile your document, but until then it should +result in a noticeably brisker display of previews if the checkbox +is cleared. + +\section{Mathed} + +(Mathed = the \LyX{} mathematics editor.) If you have instant preview +\emph{on} then one way to use \texttt{numerica} in \LyX{} is to enter +an \verb`\eval` command in mathed. Clicking the cursor outside the +editor with the mouse or moving it outside with the arrow keys will +then trigger formation of a preview of the editor's contents – a snippet +of what will be shown in the pdf. This will be displayed in mathed's +place after a generally short `pause for thought' as the mini-\LaTeX{} +run progresses behind the scenes. + +The original expression can be recovered by clicking on the preview. +The content of mathed is immediately displayed and can be edited. + +\subsection{\protect\LaTeX{} braces~\{~~\}} + +\LyX{} does not support \texttt{numerica}'s \verb`\eval` command `out +of the box' as it does, say, \verb`\frac` or \verb`\sqrt`. To use +the \verb`\eval` command in mathed you will need to supply the braces +used to delimit its mandatory argument. (For \verb`\frac` and \verb`\sqrt` +by contrast, \LyX{} supplies these automatically.) Unfortunately the +\verb`{` key\footnote{\textsf{Shift+{[}} on my keyboard.} does not +insert a left brace into the document but rather an escaped left brace +\verb`\{` as you can see by looking at \textsf{View \lyxarrow{} Code +Preview Pane}. Escaped braces like this are used for grouping terms +in \emph{mathematics}; they are not the delimiters of a \LaTeX{} argument. + +The brace delimiters for \LaTeX{} arguments are entered in mathed by +typing a backslash \textsf{\textbackslash{} }then\textsf{ \{} (two +separate key presses rather than a single combined press). This enters +a balanced pair of (unescaped) braces with the cursor sitting between +them waiting for input. Alternatively, if you have already written +an expression that you want to place between braces, select it, then +type \textsf{\textbackslash{} }then\textsf{ \{}. + +\section{Preview insets vs mathed} + +There are problems with using mathed for calculations. +\begin{itemize} +\item Expressions entered in mathed are necessarily of the form \verb`$ \eval... $` +or more generally \verb`delimiter` \verb`\eval...` \verb`delimiter`. +But you may wish to wrap the \verb`\eval` command \emph{around} the +math delimiters to produce a \emph{formula=result} form of display. +In mathed the only way to do that is to write the \emph{formula= }part +yourself – which may involve no more than copy and paste but is still +additional mouse work/key pressing. +\item Mathed does not accept carriage returns. If you want to format a complicated +expression for readability by breaking it into separate lines, you +can't. The expression is jammed into the one line, along with the +settings option content and the vv-list. +\end{itemize} +For these reasons I have come to prefer \emph{not} using mathed for +calculations but instead to use preview insets wrapped around \TeX -code +(ERT) insets. \LyX{} uses the shortcut \textsf{Ctrl+L} to insert an +ERT inset. Since \LyX{} now does no printing itself, the shortcut \textsf{Ctrl+P} +that was formerly used for printing is available for other purposes. +On my keyboard, the \textsf{P} key lies diagonally up and to the right +but adjacent to the \textsf{L} key. I suggest assigning \textsf{Ctrl+P} +to inserting a preview inset. Then typing \textsf{Ctrl+P Ctrl+L} – +which means holding the \textsf{Ctrl} key down and tapping two adjacent +keys, \textsf{P} followed immediately by \textsf{L} – will insert +an ERT inset inside a preview inset with the cursor sitting inside +the ERT inset waiting for input. In the ERT inset you can enter carriage +returns, and so format complicated expressions. You can place the +vv-list on a separate line or onto consecutive lines. And when you +have finished, clicking outside the preview inset will trigger preview +into doing its thing and present the result `before your eyes'. + +To assign the suggested shortcut, go to \textsf{Tools \lyxarrow{} Preferences +\lyxarrow{} Editing \lyxarrow{} Shortcuts}. Under \textsf{Cursor, Mouse +and Editing Functions} in the main window on the right, scroll down +until you come to \textsf{preview-insert}, select it, then click \textsf{Modify}. +Now press \textsf{Ctrl+P}. The shortcut will magically appear in the +greyed, depressed key.\textsf{ }Click \textsf{OK} and then \textsf{OK} +in the \textsf{Preferences} window to close it. (Most of the examples +in this document have been evaluated in this way, using \textsf{Ctrl+P +Ctrl+L.)} + +\section{Errors } + +Instant preview will display \texttt{numerica} error messages in \LyX{} +just as it does the results of calculations. Clicking on the message +will show the underlying expression which can then be edited. However +\LaTeX{} errors will \emph{not} produce a preview; formation of the +preview will stall. To find precisely what has gone wrong, you will +need to look at the \LaTeX{} log, but not the log of the overall document; +rather the \emph{preview} log. Unfortunately this is tucked away in +a temporary directory and is not immediately accessible in \LyX{} (unlike +the main \LaTeX{} log from \textsf{Document \lyxarrow{} \LaTeX{} Log}). +When \LyX{} is started, it sets up a temporary directory in which to +perform various tasks. On Windows systems this will be located in +\texttt{C:\textbackslash Users\textbackslash <your name>\textbackslash AppData\textbackslash Local\textbackslash Temp} +and will have a name like \texttt{lyx\_tmpdir.XOsSGhBc1344}. + +One of the tasks \LyX{} uses this temporary directory for is to create +preview images when a document is opened. If you look inside \LyX 's +temporary directory when a document is first loaded, you will see +a subdirectory created, with a name like \texttt{lyx\_tmpbuf0}. There +may already be such directories there, in which case the number on +the end will be greater than \texttt{0} – it depends on whether other +documents are or have been open in the current instance of \LyX . +Inside the appropriate \texttt{lyx\_tmpbuf}\texttt{\emph{n}} folder +will be the preview log with a name like \texttt{lyxpreviewZL1344.log}. +It will usually be accompanied by other files with extensions like +\texttt{.dvi}, \texttt{.tex}, and perhaps quite a number with the +extension \texttt{.png}, each one of which is a preview, or part of +a preview. For a document just loaded there will be only the one preview +log, but if you have added preview insets or math insets to your document\textsf{ +}in the current editing session there will be a number of such logs +and you will need to determine the relevant one by the time stamp. + +The log files are text files and can be opened in a text editor. The +relevant part of the log is towards the end (just before the final +statistical summary) where you will find a list of entries like \texttt{Preview: Snippet +1 641947 163840 7864588}. If there is an error, it will be noted here +among these snippets and will generally make clear what needs remedying. + +\subsection{CPU usage, \protect\LaTeX{} processes} + +It is possible when a preview fails to resolve that the \LaTeX{} process +associated with the preview will continue to run, using CPU cycles, +slowing overall computer performance, and perhaps resulting in extra +fan use giving a different sound to the computer. In Windows 10, the +\textsf{Task Manager} (\textsf{Ctrl+Shift+esc}) under the \textsf{Details} +tab shows the current executables running. The \textsf{CPU} column +will show which processes are preoccupying the CPU. Check whether +one or more of these processes looks \LaTeX -related (e.g. \texttt{latex.exe} +or \texttt{pdflatex.exe}, or \texttt{miktex-pdftex.exe} if using MiK\TeX ). +Click the \textsf{Name} column to sort the processes by name and look +for the relevant name in the list, select it, and end the process +(click the \textsf{End Task} button). + +I am not familiar with the corresponding situation on Linux or Mac. + +\section{Using \texttt{\textbackslash nmcReuse}} + +As noted, \LyX{} creates its previews in a temporary directory, not +the document directory. If you want to save values from your current +document – say, \texttt{mydoc.lyx} – to \texttt{mydoc.nmc} then you +can do so without drama, but \texttt{mydoc.nmc} will be located in +the temporary directory, and when \LyX{} is closed will be deleted +along with the temporary directory. + +Suppose first that at the end of a session you manually copy \texttt{mydoc.nmc} +back to the document directory. How can you ensure that the values +saved in this file are available the next time you open \texttt{mydoc.lyx}? +As noted at the start of this chapter entering +\begin{lyxcode} +\textbackslash usepackage{[}lyx{]}\{numerica\} + +\textbackslash nmcReuse +\end{lyxcode} +in the preamble ensures that these saved values are available for +use from the outset – available to the mini-\LaTeX{} runs creating +previews in the temporary directory. + +That leaves the problem of saving new values from the current session, +which are stored in \texttt{mydoc.nmc} in the \emph{temporary} directory,\texttt{ +}back to \texttt{mydoc.nmc} in the \emph{document} directory. When +\LyX{} is closed the temporary directory with all its contents is deleted. +As suggested already we could manually copy \texttt{mydoc.nmc} from +the temporary directory to the document directory but that means remembering +to do so before closing \LyX . Inevitably we will sometimes forget. + +Fortunately \LyX{} has a copying mechanism for getting files out of +the temporary directory. When a document is exported – say to pdf +– it is possible to specify a \emph{copier} to automatically copy +back to the document directory or subdirectory various files in the +temporary directory. We want the \texttt{.nmc} file containing the +saved values to be copied back. Go to \textsf{Tools \lyxarrow{} Preferences +\lyxarrow{} File Handling \lyxarrow{} File Formats} and find \textsf{PDF +(pdflatex)} (assuming export to \texttt{pdf} by this route) in the +list of formats. In\textsf{ }the \textsf{Copier} slot of the dialogue +insert the following line of code: +\begin{lyxcode} +{\small python~-tt~\$\$s/scripts/ext\_copy.py~-e~nmc,pdf~-d~\$\$i~\$\$o}{\small\par} +\end{lyxcode} +\verb`ext_copy.py` is a python script that is supplied with \LyX . +The \texttt{-e nmc,pdf -d} part of the line tells \texttt{ext\_copy.py} +that on export to \texttt{pdf} by the \texttt{pdflatex} route\texttt{ +}to copy any files with the extensions \texttt{.nmc} or \texttt{.pdf} +from the temporary directory where \LyX{} does its work back to the +document directory – the \verb`-d` option (which became available +from \LyX{} 2.3.0). + +But if you have a complex document, it may take too much time to want +to export to pdf before closing \LyX , particularly if there are a +lot of evaluations in the document. Much faster is to export to \emph{plain +text}, not because you want a plain text version of your document +but because it too can be used to trigger the copier mechanism. Go +to \textsf{Tools \lyxarrow{} Preferences \lyxarrow{} File Handling \lyxarrow{} +File Formats} and find \textsf{Plain text} in the list of formats. +In the \textsf{Copier} slot enter +\begin{lyxcode} +{\small python~-tt~\$\$s/scripts/ext\_copy.py~-e~nmc~-d~\$\$i~\$\$o}{\small\par} +\end{lyxcode} +The only difference from the previous copier command is the absence +of \texttt{pdf}.\footnote{I'm assuming that you don't actually want the plain text version of +the file copied back. If you do, then change \texttt{-e nmc} to \texttt{-e +nmc,txt}.} This will copy \texttt{mydoc.nmc} with its saved values from the +temporary directory back to the document directory. To effect the +export, go to \textsf{File \lyxarrow{} Export }and find \textsf{Plain +text} in the list of formats and click on it. + +A shortcut would be nice. For that go to \textsf{Tools \lyxarrow{} +Preferences \lyxarrow{} Editing \lyxarrow{} Shortcuts}, click on \textsf{New}, +enter \texttt{buffer-export text} in the \textsf{Function:} slot, +click on the blank key against \textsf{Shortcut:} and type your shortcut. +You may have to try a number before you find one that hasn't already +been assigned. (I'm using \textsf{Ctrl+}; for no particular reason +beyond the fact that it fits under the fingers easily and saving values +to the document directory has a punctuation-like feel to it, a pause +in the process of writing.) It is now an easy matter to press the +shortcut at the end of a \LyX{} session to copy all the values saved +in \texttt{mydoc.nmc} back to a file of the same name in the document +directory. And it is brisk, not least because plain text export ignores +ERT insets (and hence preview insets wrapped around ERT insets), nor +does it evaluate \verb`\eval` commands in math insets. + +\subsection{A final tweak?} + +But one still needs to \emph{remember} to press the shortcut. The +thought arises: can \emph{closing} the current document trigger the +copying process? \LyX{} provides a means of linking two commands and +assigning a keyboard shortcut to them with its \texttt{command-sequence} +\LyX{} function. I suggest assigning a shortcut\textsf{ }to +\begin{lyxcode} +command-sequence~buffer-export~text;~view-close +\end{lyxcode} +Indeed, why not reassign the current shortcut for \texttt{view-close},\texttt{ +}which is \textsf{Ctrl+W} on my system, to this command sequence? +(I use the \texttt{cua} key bindings – check the \textsf{Bind file:} +slot in \textsf{Tools \lyxarrow{} Preferences \lyxarrow{} Editing \lyxarrow{} +Shortcuts}.) + +Please note, however, that \emph{this will work as intended only from +\LyX{} 2.4.0}.\footnote{Due for release in the first half of 2021.} +For \LyX{} 2.3 and earlier, the command sequence will generally fail +because of `asynchronous' processing – \texttt{buffer-export }and +\texttt{view-close} use different threads and the latter may well +start before the former is complete. From \LyX{} 2.4.0 this defect +has been fixed. You press your shortcut, the export to plain text +occurs and the \texttt{.nmc} file is copied back to the document directory, +then the current view is closed. + +\section{Using \protect\LyX{} notes} + +The central fact about a \LyX{} note is that it does not contribute +to the pdf. But instant preview still works there. This suggests a +possibility: that a calculation be performed within a \LyX{} note and +the result saved using \verb`\nmcReuse` within the same preview inset. +The saved value is now available \emph{from file} for use elsewhere +in the document. In this way, some selected content from a LyX note +\emph{can} find its way into the pdf when the document is compiled. + +\chapter{Reference summary} + +\section{Commands defined in \texttt{numerica}} +\begin{enumerate} +\item \texttt{\textbackslash nmcEvaluate, \textbackslash eval } +\item \texttt{\textbackslash nmcInfo, \textbackslash info, } +\item \texttt{\textbackslash nmcReuse, \textbackslash reuse} +\item \texttt{\textbackslash q, \textbackslash Q }(`cleave' commands) +\end{enumerate} +Provided they have not already been defined when \texttt{numerica} +is loaded, the following commands are defined in \texttt{numerica} +using \verb`\DeclareMathOperator` from \texttt{amsmath} : +\begin{enumerate} +\item \texttt{\textbackslash arccsc, \textbackslash arcsec, \textbackslash arccot} +\item \texttt{\textbackslash csch, \textbackslash sech} +\item \texttt{\textbackslash asinh, \textbackslash acosh, \textbackslash atanh, +\textbackslash acsch, \textbackslash asech, \textbackslash acoth} +\item \texttt{\textbackslash sgn, \textbackslash lb} +\end{enumerate} +Provided they have not already been defined, the following commands +are defined in \texttt{numerica} using \verb`\DeclarePairedDelimiter` +from \texttt{mathtools}: +\begin{lyxcode} +\textbackslash abs,~\textbackslash ceil,~\textbackslash floor +\end{lyxcode} +The following commands have been redefined in \texttt{numerica} to +give more spacing around the underlying \verb`\wedge` and \verb`\vee` +symbols: +\begin{lyxcode} +\textbackslash land,~\textbackslash lor +\end{lyxcode} + +\section{\textquoteleft Digestible\textquoteright{} content} + +\texttt{numerica} knows how to deal with the following content, meaning +that any of these elements occurring within an \verb`\eval` command +should not of itself cause a \texttt{numerica} error. Not all formatting +commands affect display of the output. +\begin{enumerate} +\item variable names (sequences of tokens given values in the variable~=~value +list) +\item digits, decimal point +\begin{enumerate} +\item \texttt{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, .} +\end{enumerate} +\item constants +\begin{enumerate} +\item \texttt{e, \textbackslash pi, \textbackslash gamma, \textbackslash phi, +\textbackslash deg, \textbackslash infty }(sometimes) +\end{enumerate} +\item arithmetic operators +\begin{enumerate} +\item \texttt{+, -, {*}, /, \textasciicircum , \textbackslash times, \textbackslash cdot, +\textbackslash div} +\end{enumerate} +\item logical operators +\begin{enumerate} +\item \texttt{\textbackslash wedge, \textbackslash land, \textbackslash vee, +\textbackslash lor, \textbackslash neg, \textbackslash lnot} +\end{enumerate} +\item comparisons +\begin{enumerate} +\item \texttt{=, <, >, \textbackslash ne, \textbackslash neq, \textbackslash le, +\textbackslash leq, \textbackslash ge, \textbackslash geq} +\item (if \texttt{amssymb} loaded) \texttt{\textbackslash nless, \textbackslash ngtr, +\textbackslash geqq, \textbackslash geqslant, \textbackslash leqq, +\textbackslash leqslant, \textbackslash ngeq, \textbackslash ngeqq, +\textbackslash ngeqslant, \textbackslash nleq, \textbackslash nleqq, +\textbackslash nleqslant} +\end{enumerate} +\item brackets, bracket-like elements, modifiers +\begin{enumerate} +\item \texttt{( ), {[} {]}, \textbackslash\{ \textbackslash\}} +\item \texttt{\textbackslash lparen \textbackslash rparen} (from \texttt{mathtools})\texttt{, +\textbackslash lbrack \textbackslash rbrack, \textbackslash lbrace +\textbackslash rbrace} +\item \texttt{\textbackslash lvert \textbackslash rvert, \textbackslash lfloor +\textbackslash rfloor, \textbackslash lceil \textbackslash rceil} +\item \texttt{| |} (no nesting, deprecated) +\item \texttt{\textbackslash left \textbackslash right, \textbackslash bigl +\textbackslash bigr, \textbackslash Bigl \textbackslash Bigr, \textbackslash biggl +\textbackslash biggr, \textbackslash Biggl \textbackslash Biggr} +\item \texttt{.} \texttt{/ |} (used with a modifier) +\item \texttt{\textbackslash abs{[}{]}\{\}, \textbackslash abs{*}\{\}, +\textbackslash floor{[}{]}\{\}, \textbackslash floor{*}\{\}, \textbackslash ceil{[}{]}\{\}, +\textbackslash ceil{*}\{\}} +\end{enumerate} +\item unary functions (in the mathematical sense) +\begin{enumerate} +\item \texttt{\textbackslash sin, \textbackslash cos, \textbackslash tan, +\textbackslash csc, \textbackslash sec, \textbackslash cot} +\item \texttt{\textbackslash arcsin, \textbackslash arccos, \textbackslash arctan, +arccsc, \textbackslash arcsec, \textbackslash arccot } +\item \texttt{\textbackslash sin\textasciicircum\{-1\}, \textbackslash cos\textasciicircum\{-1\}, +\textbackslash tan\textasciicircum\{-1\}, \textbackslash csc\textasciicircum\{-1\}, +\textbackslash sec\textasciicircum\{-1\}, \textbackslash cot\textasciicircum\{-1\}} +\item \texttt{\textbackslash sinh, \textbackslash cosh, \textbackslash tanh, +\textbackslash csch, \textbackslash sech, \textbackslash coth } +\item \texttt{\textbackslash asinh, \textbackslash acosh, \textbackslash atanh, +\textbackslash csch, \textbackslash sech, \textbackslash acoth} +\item \texttt{\textbackslash sinh\textasciicircum\{-1\}, \textbackslash cosh\textasciicircum\{-1\}, +\textbackslash tanh\textasciicircum\{-1\}, \textbackslash csch\textasciicircum\{-1\}, +\textbackslash sech\textasciicircum\{-1\}, \textbackslash acoth\textasciicircum\{-1\}} +\item \texttt{\textbackslash exp, \textbackslash lb, \textbackslash lg, +\textbackslash ln, \textbackslash log, \textbackslash log\_\{\}, +\textbackslash sgn, \textbackslash surd} +\item \texttt{\textbackslash sqrt\{\}, \textbackslash abs{[}{]}\{\}, \textbackslash abs{*}\{\}, +\textbackslash floor{[}{]}\{\}, \textbackslash floor{*}\{\}, \textbackslash ceil{[}{]}\{\}, +\textbackslash ceil{*}\{\}} +\item \texttt{!, !! }(prepended argument) +\end{enumerate} +\item binary functions +\begin{enumerate} +\item \texttt{\textbackslash tfrac\{\}\{\}, \textbackslash frac\{\}\{\}, +\textbackslash dfrac\{\}\{\}} +\item \texttt{\textbackslash tbinom\{\}\{\}, \textbackslash binom\{\}\{\}, +\textbackslash dbinom\{\}\{\}} +\item \texttt{\textbackslash sqrt{[}{]}\{\}} +\end{enumerate} +\item $n$-ary functions +\begin{enumerate} +\item \texttt{\textbackslash min, \textbackslash max, \textbackslash gcd} +\end{enumerate} +\item sum, prod +\begin{enumerate} +\item \texttt{\textbackslash sum\_\{\}\textasciicircum , \textbackslash prod\_\{\}\textasciicircum{} } +\end{enumerate} +\item formatting commands +\begin{enumerate} +\item \texttt{,} (comma, in $n$-ary functions) +\item \texttt{\{\}, \textbackslash\textbackslash , \&, \textbackslash to} +\item \texttt{\textbackslash dots, \textbackslash ldots, \textbackslash cdots,} +\item \texttt{\textbackslash{} , \textbackslash ,{}, \textbackslash ;, +\textbackslash :, \textbackslash !, \textbackslash >} +\item \texttt{\textbackslash thinspace, \textbackslash quad, \textbackslash qquad +, \textbackslash hfill, \textbackslash hfil} +\item \texttt{\textbackslash phantom\{\}, \textbackslash vphantom\{\}, +\textbackslash hphantom\{\}} +\item \texttt{\textbackslash xmathstrut{[}{]}\{\}} \texttt{, \textbackslash splitfrac\{\}\{\}, +\textbackslash splitdfrac\{\}\{\} }(from \texttt{mathtools}), \texttt{\textbackslash mathstrut} +\item \texttt{\textbackslash displaystyle, \textbackslash textstyle, \textbackslash scriptstyle, +\textbackslash scriptscriptstyle} +\item \texttt{\textbackslash label\{\}, \textbackslash ensuremath\{\}, +\textbackslash text\{\}, \textbackslash mbox\{\}} +\item \texttt{\textbackslash begin\{\}, \textbackslash end\{\}} +\end{enumerate} +\item font commands +\begin{enumerate} +\item \texttt{\textbackslash mathrm\{\}, \textbackslash mathit\{\}, \textbackslash mathcal\{\}, +\textbackslash mathtt\{\}, \textbackslash mathbf\{\}, \textbackslash mathbb\{\}, +\textbackslash mathsf\{\}, \textbackslash mathfrak\{\}, \textbackslash mathscr\{\}, +\textbackslash mathnormal\{\}, \textbackslash boldsymbol\{\}} +\end{enumerate} +\end{enumerate} + +\section{Settings} + +\subsection{Available \texttt{\textbackslash nmcEvaluate} settings} +\begin{center} +\begin{tabular}{ll>{\raggedright}p{4cm}>{\raggedright}p{4cm}} +\toprule +{\small key} & {\small type} & {\small meaning} & {\small default}\tabularnewline +\midrule +{\small\texttt{dbg}} & {\small int} & {\small debug `magic' integer} & {\small\texttt{0}}\tabularnewline +{\small\texttt{\textasciicircum}} & {\small char} & {\small exponent mark for sci. notation input} & {\small\texttt{e}}\tabularnewline +{\small\texttt{xx}} & {\small int (0/1)} & {\small multi-token variable switch} & {\small\texttt{1}}\tabularnewline +{\small\texttt{()}} & {\small int (0/1/2)} & {\small trig. function arg. parsing} & {\small\texttt{0}}\tabularnewline +{\small\texttt{o}} & & {\small degree switch for trig. funcions} & \tabularnewline +{\small\texttt{log}} & {\small num} & {\small base of logarithms for }{\small{\small\verb`\log`}} & {\small\texttt{10}}\tabularnewline +{\small\texttt{vvmode}} & {\small int (0/1)} & {\small vv-list calculation mode} & {\small\texttt{0}}\tabularnewline +{\small\texttt{vvd}} & {\small token(s)} & {\small vv-list display-style spec.} & {\small\texttt{\{,\}\textbackslash mskip 12mu plus 6mu minus 9mu(vv)}}\tabularnewline +{\small\texttt{vvi}} & {\small token(s)} & {\small vv-list text-style spec.} & {\small\texttt{\{,\}\textbackslash mskip 36mu minus 24mu(vv)}}\tabularnewline +{*} & & {\small switch to suppress equation numbering (if }{\small\texttt{\textbackslash\textbackslash}}{\small{} +in }{\small\texttt{vvd}}{\small )} & \tabularnewline +{\small\texttt{p}} & char(s) & {\small punctuation (esp. in display-style)} & {\small\texttt{,}}\tabularnewline +{\small\texttt{S+}} & {\small int} & {\small extra rounding for stopping criterion, sums} & {\small\texttt{2}}\tabularnewline +{\small\texttt{S?}} & {\small$\text{int}\ge0$} & {\small query stopping with these final terms, sums} & {\small\texttt{0}}\tabularnewline +{\small\texttt{P+}} & {\small int} & {\small extra rounding for stopping criterion, products} & {\small\texttt{2}}\tabularnewline +{\small\texttt{P?}} & {\small$\text{int}\ge0$} & {\small query stopping with these final terms, products} & {\small\texttt{0}}\tabularnewline +{\small\texttt{reuse}} & {\small int} & {\small form of result saved with }{\small{\small\verb`\nmcReuse`}} & {\small\texttt{0}}\tabularnewline +\bottomrule +\end{tabular} +\par\end{center} + +\subsection{Available configuration file settings} +\begin{center} +\bigskip{} +\begin{tabular}{ll} +\toprule +key & default\tabularnewline +\midrule +{\small\texttt{rounding}} & {\small\texttt{6}}\tabularnewline +{\small\texttt{pad}} & {\small\texttt{0}}\tabularnewline +{\small\texttt{output-sci-notation}} & {\small\texttt{0}}\tabularnewline +{\small\texttt{output-exponent-char}} & {\small\texttt{e}}\tabularnewline +{\small\texttt{input-sci-notation}} & {\small\texttt{0}}\tabularnewline +{\small\texttt{input-exponent-char}} & {\small\texttt{e}}\tabularnewline +{\small\texttt{multitoken-variables}} & {\small\texttt{1}}\tabularnewline +{\small\texttt{logarithm-base}} & {\small\texttt{10}}\tabularnewline +{\small\texttt{intify-rounding}} & {\small\texttt{14}}\tabularnewline +{\small\texttt{vv-display}} & {\small\texttt{\{,\}\textbackslash mskip 36mu minus 24mu(vv)}}\tabularnewline +{\small\texttt{vv-inline}} & {\small\texttt{\{,\}\textbackslash mskip 12mu plus 6mu minus 9mu(vv)}}\tabularnewline +{\small\texttt{sum-extra-rounding}} & {\small\texttt{2}}\tabularnewline +{\small\texttt{sum-query-terms}} & {\small\texttt{0}}\tabularnewline +{\small\texttt{prod-extra-rounding}} & {\small\texttt{2}}\tabularnewline +{\small\texttt{prod-query-terms}} & {\small\texttt{0}}\tabularnewline +{\small\texttt{eval-reuse}} & {\small\texttt{0}}\tabularnewline +\bottomrule +\end{tabular} +\par\end{center} +\end{document} |