Debian Codegraph @

texmf-dist/doc/generic/pgf/pgfmanual-en-library-math.tex

raw
1 % Copyright 2019 by Mark Wibrow
2 %
3 % This file may be distributed and/or modified
4 %
5 % 1. under the LaTeX Project Public License and/or
6 % 2. under the GNU Free Documentation License.
7 %
8 % See the file doc/generic/pgf/licenses/LICENSE for more details.
9
10
11 \section{Math Library}
12 \label{section-library-math}
13
14 \begin{tikzlibrary}{math}
15 This library defines a simple mathematical language to define simple
16 functions and perform sequences of basic mathematical operations.
17 \end{tikzlibrary}
18
19
20 \subsection{Overview}
21
22 \pgfname\ and \tikzname\ both use the \pgfname\ mathematical engine which
23 provides many commands for parsing expressions. Unfortunately the \pgfname\
24 math engine is somewhat cumbersome for long sequences of mathematical
25 operations, particularly when assigning values to multiple variables. The
26 \tikzname\ |calc| library provides some additional ``convenience'' operations
27 for doing calculations (particularly with coordinates), but this can only be
28 used inside \tikzname\ path commands.
29
30 This |math| library provides a means to perform sequences of mathematical
31 operations in a more `user friendly' manner than the \pgfname\ math engine. In
32 addition, the coordinate calculations of the |calc| library can be accessed
33 (provided it is loaded).
34 %
35 However as the |math| library uses the \pgfname\ math engine -- which uses pure
36 \TeX\ to perform all its calculations -- it is subject to the same speed and
37 accuracy limitations. It is worth bearing this in mind, before trying to
38 implement algorithms requiring intensive and highly accurate computation. You
39 can, of course use the |fp| or the |fpu| libraries to increase the accuracy
40 (but not necessarily the speed) of computations.
41
42 For most purposes, the features provided by this library are accessed using the
43 following command:
44
45 \begin{command}{\tikzmath\texttt{\{}\meta{statements}\texttt{\}}}
46 This command process a series of \meta{statements} which can represent
47 assignments, function definitions, conditional evaluation, and iterations.
48 It provides, in effect, a miniature mathematical language to perform basic
49 mathematical operations. Perhaps the most important thing to remember is
50 that \emph{every statement should end with a semi-colon}. This is likely to
51 be the most common reason why the |\tikzmath| command fails.
52 %
53 \begin{codeexample}[preamble={\usetikzlibrary{math}}]
54 \tikzmath{
55 % Adapted from http://www.cs.northwestern.edu/academics/courses/110/html/fib_rec.html
56 function fibonacci(\n) {
57 if \n == 0 then {
58 return 0;
59 } else {
60 return fibonacci2(\n, 0, 1);
61 };
62 };
63 function fibonacci2(\n, \p, \q) {
64 if \n == 1 then {
65 return \q;
66 } else {
67 return fibonacci2(\n-1, \q, \p+\q);
68 };
69 };
70 int \f, \i;
71 for \i in {0,1,...,20} {
72 \f = fibonacci(\i);
73 print {\f, };
74 };
75 }
76 \end{codeexample}
77 %
78 \end{command}
79
80 In addition to this command the following key is provided:
81
82 \begin{key}{/tikz/evaluate={\meta{statements}}}
83 This key simply executes |\tikzmath{|\meta{statements}|}|.
84 %
85 \begin{codeexample}[preamble={\usetikzlibrary{math}}]
86 \tikz[x=0.25cm,y=0.25cm,
87 evaluate={
88 int \i, \j;
89 for \i in {0,...,10} {
90 for \j in {0,...,10} {
91 \a{\i,\j} = (\i+\j)*5;
92 };
93 };
94 }
95 ]
96 \foreach \i in {0,...,10}
97 \foreach \j in {0,...,10}
98 \fill [red!\a{\i,\j}!yellow] (\i,\j) rectangle ++(1, 1);
99 \end{codeexample}
100 %
101 \end{key}
102
103 The following sections describe the miniature language that this library
104 provides and can be used in the |\tikzmath| command and the |evaluate| key.
105 The language consists only of simple keywords and expressions but the
106 mini-parser allows you to format code in a reasonably versatile way (much like
107 the |tikz| parser) except that \emph{all the keywords must be followed by at
108 least one space}. This is the second most important thing to remember (after
109 remembering to insert semi-colons at the end of every statement).
110
111
112 \subsection{Assignment}
113
114 In the simplest case, you will want to evaluate an expression and assign it to
115 a macro, or a \TeX\ count or dimension register. In this case, use of the
116 |math| library is straightforward:
117 %
118 \begin{codeexample}[preamble={\usetikzlibrary{math}}]
119 \newcount\mycount
120 \newdimen\mydimen
121 \tikzmath{
122 \a = 4*5+6;
123 \b = sin(30)*4;
124 \mycount = log10(2048) / log10(2);
125 \mydimen = 15^2;
126 }
127 \a, \b, \the\mycount, \the\mydimen
128 \end{codeexample}
129
130 In addition, \TeX-macros (\emph{not} \TeX\ registers) can be suffixed with an
131 index, similar to indices in mathematical notation, for example, $x_1$, $x_2$,
132 $x_3$:
133 %
134 \begin{codeexample}[preamble={\usetikzlibrary{math}}]
135 \tikzmath{
136 \x1 = 3+4; \x2 = 30+40; \x3 = 300+400;
137 }
138 \x1, \x2, \x3
139 \end{codeexample}
140
141 The index does not have to be a number. By using braces |{}|, more
142 sophisticated indices can be created:
143 %
144 \begin{codeexample}[preamble={\usetikzlibrary{math}}]
145 \tikzmath{
146 \c{air} = 340; \c{water} = 1435; \c{steel} = 6100;
147 }
148 \foreach \medium in {air,steel}{The speed of sound in \medium\ is \c{\medium} m/s. }
149 \end{codeexample}
150
151 You should not, however, try to mix indexed and non-indexed variables. Once an
152 assignment is made using an index, the |math| library expects all instances of
153 the variable on the right hand side of an assignment to be followed by an
154 index. This effect is reversed if you subsequently make an assignment to the
155 variable without an index: the |math| library (or to be precise the \pgfname\
156 math-engine) will then ignore any index following the variable on the right
157 hand side of an assignment.
158
159 In some cases, you may wish to assign a value or expression to a variable
160 without evaluating it with the \pgfname\ math-engine. In this case, you can use
161 the following keyword:
162
163 \begin{math-keyword}{{let} \meta{variable} \texttt{=} \meta{expression}\texttt{;}}
164 This keyword assigns \meta{expression} to \meta{variable} without
165 evaluation. The \meta{expression} is however fully expanded using |\edef|.
166 Any spaces preceding \meta{expression} are removed, but any trailing spaces
167 (before the semi-colon) are included.
168 %
169 \begin{codeexample}[preamble={\usetikzlibrary{math}}]
170 \tikzmath{
171 let \x = (5*4)+1;
172 let \c1 = blue;
173 }
174 \x, ``\c1''
175 \end{codeexample}
176 %
177 \end{math-keyword}
178
179
180 \subsection{Integers, ``Real'' Numbers, and Coordinates}
181
182 By default, assignments are made by evaluating expressions using the \pgfname\
183 math-engine and results are usually returned as number with a decimal point
184 (unless you are assigning to a count register or use the |int| function).
185 %
186 As this is not always desirable, the |math| library allows variables -- which
187 \emph{must} be \TeX\ macros -- to be `declared' as being a particular `type'.
188 The library recognizes three types: integers (numbers without a decimal point),
189 real numbers (numbers with a decimal point\footnote{Strictly speaking, due to
190 the finite range and precision of \TeX\ numerical capabilities, the term
191 ``real'' is not correct.}), and coordinates.
192
193 To declare a variable as being one of the three types, you can use the
194 keywords shown below. It is important to remember that by telling the |math|
195 library you want it to do a particular assignment for a variable, it will also
196 do the same assignment when the variable is indexed.
197 %
198 \begin{codeexample}[preamble={\usetikzlibrary{math}}]
199 \tikzmath{
200 integer \x;
201 \x1 = 3+4; \x2 = 30+40; \x3 = 300+400;
202 }
203 \x1, \x2, \x3
204 \end{codeexample}
205
206 %But, if you want integer results without using a count register or the
207 %|int| function, you can use a keyword to indicate this:
208
209 \begin{math-keyword}{{integer} \meta{variable}\opt{\texttt{,} \meta{additional variables}}\texttt{;}}
210 The |integer| keyword indicates that assignments to the \meta{variable} or
211 the comma separated list of \meta{additional variables} should be truncated
212 (not rounded) to integers. The variables should be ordinary macros --
213 \emph{not} \TeX\ registers. In addition the variables should \emph{not} be
214 indexed.
215 %
216 \begin{codeexample}[preamble={\usetikzlibrary{math}}]
217 \tikzmath{
218 integer \x, \y, \z;
219 \x = 4*5+6;
220 \y = sin(30)*4;
221 \z = log10(512) / log10(2);
222 print {$x=\x$, $y=\y$, $z=\z$};
223 }
224 \end{codeexample}
225 %
226 \end{math-keyword}
227
228 \begin{math-keyword}{{int} \meta{variable}\opt{\texttt{,} \meta{additional variables}}\texttt{;}}
229 Short version of the |integer| keyword.
230 \end{math-keyword}
231
232 Having declared a variable as an integer, the |math| library will continue to
233 assign only integers to that variable within the current \TeX\ scope. If you
234 wish to assign non-integer (i.e., \emph{real}) numbers to the same variable,
235 the following keyword can be used.
236
237 \begin{math-keyword}{{real} \meta{variable}\opt{\texttt{,} \meta{additional variables}}\texttt{;}}
238 The |real| keyword ensures that assignments \meta{variable} (and
239 \meta{additional variables}) will not be truncated to integers.
240 \end{math-keyword}
241
242 In order to take advantage of |math| library interface to the |calc| library
243 you must indicate that a variable is to be assigned coordinates, using the
244 following keyword.
245
246 \begin{math-keyword}{{coordinate} \meta{variable}\opt{\texttt{,} \meta{additional variables}}\texttt{;}}
247 This keyword enables \tikzname-style coordinates such as |(2cm,3pt)| or
248 |(my node.east)| to be parsed and assigned to \meta{variable} in the form
249 $x,y$, which can then be used in a |tikzpicture|:
250 %
251 \begin{codeexample}[preamble={\usetikzlibrary{math}}]
252 \tikzmath{
253 coordinate \c;
254 \c = (45:10pt);
255 }
256 \tikz\draw (0,0) -- (\c);
257 \end{codeexample}
258
259 If the \tikzname\ |calc| library is loaded, coordinate calculations can be
260 performed; the coordinate expression does not have to be surrounded by
261 |($|\ldots|$)|.
262 %
263 \begin{codeexample}[preamble={\usetikzlibrary{math}}]
264 \tikzmath{
265 coordinate \c, \d;
266 \c = (-1,2)+(1,-1);
267 \d = (4,1)-(2,-1);
268 }
269 \tikz\draw (\c) -- (\d);
270 \end{codeexample}
271
272 In addition to assigning the $x$ and $y$ coordinates to \meta{variable}
273 (possibly with an optional index), two further variables are defined. The
274 first takes the name of \meta{variable} (e.g., |\c|) suffixed with |x|
275 (i.e., |\cx|) and is assigned the $x$ coordinate of |\c|. The second takes
276 the name of \meta{variable} suffixed with |y| (i.e., |\cy|) and is assigned
277 the $y$ coordinate of |\c|.
278 %
279 \begin{codeexample}[preamble={\usetikzlibrary{math}}]
280 \tikzmath{
281 coordinate \c;
282 \c1 = (30:20pt);
283 \c2 = (210:20pt);
284 }
285 \tikz\draw (\cx1,\cy1) -- (\cx2,\cy1) -- (\cx2,\cy2) -- (\cx1,\cy2);
286 \end{codeexample}
287 %
288 \end{math-keyword}
289
290 %\begin{math-keyword}{{point} \meta{variable}\opt{\texttt{,} \meta{additional variables}}\texttt{;}}
291 % The |point| keyword is a synonym for the |coordinate| keyword and performs
292 % the same function.
293 %\end{math-keyword}
294
295
296 \subsection{Repeating Things}
297
298 \begin{math-keyword}{{for} \meta{variable} \texttt{in \{}\meta{list} \texttt{\}\{}\meta{expressions}\texttt{\};}}
299 This is a ``trimmed down'' version of the |\foreach| command available as
300 part of \pgfname\ and \tikzname, but cannot currently be used outside of
301 the |\tikzmath| command. It is important to note the following:
302 %
303 \begin{itemize}
304 \item Every value in \meta{list} is evaluated using the \pgfname\
305 mathematical engine. However, if an item in \meta{list} contains a
306 comma, it \emph{must} be surrounded by braces, for example,
307 |{mod(5, 2)}|.
308 %
309 \begin{codeexample}[pre={\pgfmathsetseed{1}},preamble={\usetikzlibrary{math}}]
310 \tikzmath{
311 int \x, \v;
312 \v=1;
313 for \x in {1,...,{random(3,10)}} {
314 \v=\v*2;
315 };
316 print {$x=\x, v=\v$};
317 }
318 \end{codeexample}
319 %
320 \item Because each item is evaluated, you cannot use \tikzname\
321 coordinates in \meta{list}.
322 \item Only single variable assignment is supported.
323 \item The ``dots notation'' (e.g., |1,2,...,9|) can be used in
324 \meta{list}, but is not as sophisticated as the \pgfname\
325 |\foreach| command. In particular, contextual replacement is not
326 possible.
327 \item Assignments that occur in the loop body \emph{are not scoped}.
328 They last beyond the body of each iteration and the end of the
329 |for| statement. This includes the values assigned to the
330 \meta{variable}.
331 %
332 \begin{codeexample}[preamble={\usetikzlibrary{math}}]
333 \tikzmath{
334 int \x, \y;
335 \y = 0;
336 for \x1 in {1,...,5} {
337 for \x2 in {10,20,...,50} {
338 \y = \y+\x1*\x2;
339 };
340 };
341 }
342 $x_1=\x1, x_2=\x2, y=\y$
343 \end{codeexample}
344 \end{itemize}
345 \end{math-keyword}
346
347
348 \subsection{Branching Statements}
349
350 Sometimes you may wish to execute different statements depending on the value
351 of an expression. In this case the following keyword can be used:
352
353 \begin{math-keyword}{{if} \meta{condition} \texttt{then \{}\meta{if-non-zero-statements}\texttt{\};}}
354 This keyword executes \meta{if-non-zero-statements} if the expression in
355 \meta{condition} evaluates to any value other than zero.
356 \end{math-keyword}
357
358 \begin{math-keyword}{{if} \meta{condition} \texttt{then \{}\meta{if-non-zero-statements}\texttt{\}} \texttt{else} \texttt{\{}\meta{if-zero-statements}\texttt{\}}\texttt{;}}
359 This keyword executes \meta{if-non-zero-statements} if the expression in
360 \meta{condition} evaluates to any value other than zero and the
361 \meta{if-zero-statements} are executed if the expression in
362 \meta{condition} evaluates to zero.
363 %
364 \begin{codeexample}[preamble={\usetikzlibrary{math}}]
365 \begin{tikzpicture}
366 \tikzmath{
367 int \x;
368 for \k in {0,10,...,350} {
369 if \k>260 then { let \c = orange; } else {
370 if \k>170 then { let \c = blue; } else {
371 if \k>80 then { let \c = red; } else {
372 let \c = green; }; }; };
373 {
374 \path [fill=\c!50, draw=\c] (\k:0.5cm) -- (\k:1cm) --
375 (\k+5:1cm) -- (\k+5:0.5cm) -- cycle;
376 };
377 };
378 }
379 \end{tikzpicture}
380 \end{codeexample}
381 %
382 \end{math-keyword}
383
384
385 \subsection{Declaring Functions}
386
387 You can add functions by using the following keywords:
388
389 \begin{math-keyword}{{function} \meta{name}\texttt{(}\meta{arguments}\texttt{) \{} \meta{definition} \texttt{\};}}
390 This keyword works much like the |declare function| provided by the
391 \pgfname\ math-engine. The function \meta{name} can be any name that is not
392 already a function name in the current scope. The list of \meta{arguments}
393 are comma separated \TeX\ macros such as |\x|, or |\y| (it is not possible
394 to declare functions that take variable numbers of arguments). If the
395 function takes no arguments then the parentheses need not be used. It is
396 very important to note that the arrays that the \pgfname\ math engine
397 supports \emph{cannot currently be passed as arguments to functions}.
398
399 The function \meta{definition} should be a sequence of statements that can
400 be parsed by the |\tikzmath| command and should use the commands specified
401 in the \meta{arguments}. The |return| keyword (described below) should be
402 used to indicate the value returned by the function.
403 %
404 Although \meta{definition} can take any statements accepted by |\tikzmath|,
405 it is not advisable try to define functions inside other functions.
406 %
407 \begin{codeexample}[pre={\pgfmathsetseed{1}},preamble={\usetikzlibrary{math}}]
408 \tikzmath{
409 function product(\x,\y) {
410 return \x*\y;
411 };
412 int \i, \j, \k;
413 \i = random(1,10);
414 \j = random(20, 40);
415 \k = product(\i, \j);
416 print { $\i\times \j = \k$ };
417 }
418 \end{codeexample}
419 %
420 \end{math-keyword}
421
422 \begin{math-keyword}{{return} \meta{expression}\texttt{;}}
423 This keyword should be used as the last executed statement in a function
424 definition to indicate the value that should be returned.
425 \end{math-keyword}
426
427
428 \subsection{Executing Code Outside the Parser}
429
430 Sometimes you may wish to do ``something'' outside the parser, perhaps display
431 some intermediate result or execute some code. In this case you have two
432 options. Firstly, the following keyword can be used:
433
434 \begin{math-keyword}{{print} \texttt{\{}\meta{code}\texttt{\};}}
435 Execute \meta{code} immediately. This is intended as convenience keyword
436 for displaying information in a document (analogous to the |print| command
437 in real programming languages). The \meta{code} is executed inside a \TeX\
438 group.
439 %
440 \begin{codeexample}[pre={\pgfmathsetseed{1}},preamble={\usetikzlibrary{math}}]
441 \tikzmath{
442 int \x, \y, \z;
443 \x = random(2, 5);
444 for \y in {0,...,6} {
445 \z = \x^\y;
446 print {$\x^\y=\z$, };
447 };
448 }
449 \end{codeexample}
450 %
451 \end{math-keyword}
452
453 Secondly, if a statement begins with a brace |{|, then everything up to the
454 closing brace |}| is collected and executed (the closing brace \emph{must} be
455 followed by a semi-colon). Like the |print| keyword, the contents of the braces
456 is executed inside a \TeX\ group. Unlike the |print| keyword, the brace
457 notation can be used in functions so that |tikz| path commands can be safely
458 executed inside a |tikzpicture|.
459 %
460 \begin{codeexample}[preamble={\usetikzlibrary{math}}]
461 \begin{tikzpicture}
462 \draw [help lines] grid (3,2);
463 \tikzmath{
464 coordinate \c;
465 for \x in {0,10,...,360} {
466 \c = (1.5cm, 1cm) + (\x:1cm and 0.5cm);
467 { \fill (\c) circle [radius=1pt]; };
468 };
469 }
470 \end{tikzpicture}
471 \end{codeexample}