The TikZ and PGF Packages
Manual for version 3.1.10
Mathematical and Object-Oriented Engines
94 Mathematical Expressions¶
The easiest way of using pgf’s mathematical engine is to provide a mathematical expression given in familiar infix notation, for example, 1cm+4*2cm/5.5 or 2*3+3*sin(30). This expression can be parsed by the mathematical engine and the result can be placed in a dimension register, a counter, or a macro. \(\newcommand {\mvar }[1]{#1} \)
It should be noted that all calculations must not exceed \(\pm 16383.99999\) at any point, because the underlying computations rely on TeX dimensions. This means that many of the underlying computations are necessarily approximate and, in addition, not very fast. TeX is, after all, a typesetting language and not ideally suited to relatively advanced mathematical operations. However, it is possible to change the computations as described in Section 96.
In the present section, the high-level macros for parsing an expression are explained first, then the syntax for expression is explained.
94.1 Parsing Expressions¶
94.1.1 Commands¶
The basic command for invoking the parser of pgf’s mathematical engine is the following:
-
\pgfmathparse{⟨expression⟩} ¶
-
• The result stored in the macro \pgfmathresult is a decimal without units. This is true regardless of whether the ⟨expression⟩ contains any unit specification. All numbers with units are converted to points first. See Section 94.1.2 for details on units.
-
• The parser will recognize TeX registers and box dimensions, so \mydimen, 0.5\mydimen, \wd\mybox, 0.5\dp\mybox, \mycount\mydimen and so on can be parsed.
-
• The \(\varepsilon \)-TeX extensions \dimexpr, \numexpr, \glueexpr, and \muexpr are recognized and evaluated. The values they result in will be used in the further evaluation, as if you had put \the before them.
-
• Parenthesis can be used to change the order of the evaluation.
-
• Various functions are recognized, so it is possible to parse sin(.5*pi r)*60, which means “the sine of \(0.5\) times \(\pi \) radians, multiplied by 60”. The argument of functions can be any expression.
-
• Scientific notation in the form 1.234e+4 is recognized (but the restriction on the range of values still applies). The exponent symbol can be upper or lower case (i.e., E or e).
-
• An integer with a zero-prefix (excluding, of course zero itself), is interpreted as an octal number and is automatically converted to base 10.
-
• An integer with prefix 0x or 0X is interpreted as a hexadecimal number and is automatically converted to base 10. Alphabetic digits can be in uppercase or lowercase.
-
• An integer with prefix 0b or 0B is interpreted as a binary number and is automatically converted to base 10.
-
• An expression (or part of an expression) surrounded with double quotes (i.e., the character ") will not be evaluated. Obviously this should be used with great care.
This macro parses ⟨expression⟩ and returns the result without units in the macro \pgfmathresult.
Example: \pgfmathparse{2pt+3.5pt} will set \pgfmathresult to the text 5.5.
In the following, the special properties of this command are explained. The exact syntax of mathematical expressions is explained in Sections 94.2 and 94.3.
-
\pgfmathqparse{⟨expression⟩} ¶
This macro is similar to \pgfmathparse: it parses ⟨expression⟩ and returns the result in the macro \pgfmathresult. It differs in two respects. Firstly, \pgfmathqparse does not parse functions, scientific notation, the prefixes for binary octal, or hexadecimal numbers, nor does it accept the special use of ", ? or : characters. Secondly, numbers in ⟨expression⟩ must specify a TeX unit (except in such instances as 0.5\pgf@x), which greatly simplifies the problem of parsing real numbers. As a result of these restrictions \pgfmathqparse is about twice as fast as \pgfmathparse. Note that the result will still be a number without units.
-
\pgfmathpostparse ¶
At the end of the parse this command is executed, allowing some custom action to be performed on the result of the parse. When this command is executed, the macro \pgfmathresult will hold the result of the parse (as always, without units). The result of the custom action should be used to redefine \pgfmathresult appropriately. By default, this command is equivalent to \relax. This differs from previous versions, where, if the parsed expression contained no units, the result of the parse was scaled according to the value in \pgfmathresultunitscale (which by default was 1).
This scaling can be turned on again using: \let\pgfmathpostparse=\pgfmathscaleresult. Note, however that by scaling the result, the base conversion functions will not work, and the " character should not be used to quote parts of an expression.
Instead of the \pgfmathparse macro you can also use wrapper commands, whose usage is very similar to their cousins in the calc package. The only difference is that the expressions can be any expression that is handled by \pgfmathparse. For all of the following commands, if ⟨expression⟩ starts with +, no parsing is done and a simple assignment or increment is done using normal TeX assignments or increments. This will be orders of magnitude faster than calling the parser.
The effect of the following commands is always local to the current TeX scope.
-
\pgfmathsetlength{⟨register⟩}{⟨expression⟩} ¶
Basically, this command sets the length of the TeX ⟨register⟩ to the value specified by ⟨expression⟩. However, there is some fine print:
First, in case ⟨expression⟩ starts with a +, a simple TeX assignment is done. In particular, ⟨register⟩ can be a glue register and ⟨expression⟩ be something like +1pt plus 1fil and the ⟨register⟩ will be assigned the expected value.
Second, when the ⟨expression⟩ does not start with +, it is first parsed using \pgfmathparse, resulting in a (dimensionless) value \pgfmathresult. Now, if the parser encountered the unit mu somewhere in the expression, it assumes that ⟨register⟩ is a \muskip register and will try to assign to ⟨register⟩ the value \pgfmathresult followed by mu. Otherwise, in case mu was not encountered, it is assumed that ⟨register⟩ is a dimension register or a glue register and we assign \pgfmathresult followed by pt to it.
The net effect of the above is that you can write things like
One thing that will not work is \pgfmathsetlength{\myskip}{1pt plus 1fil} since the parser does not support fill’s. You can, however, use the + notation in this case:
-
\pgfmathaddtolength{⟨register⟩}{⟨expression⟩} ¶
Adds the value of ⟨expression⟩ to the TeX ⟨register⟩. All of the special consideration mentioned for \pgfmathsetlength also apply here in the same way.
-
\pgfmathsetcount{⟨count register⟩}{⟨expression⟩} ¶
Sets the value of the TeX ⟨count register⟩, to the truncated value specified by ⟨expression⟩.
-
\pgfmathaddtocount{⟨count register⟩}{⟨expression⟩} ¶
Adds the truncated value of ⟨expression⟩ to the TeX ⟨count register⟩.
-
\pgfmathsetcounter{⟨counter⟩}{⟨expression⟩} ¶
Sets the value of the LaTeX ⟨counter⟩ to the truncated value specified by ⟨expression⟩.
-
\pgfmathaddtocounter{⟨counter⟩}{⟨expression⟩} ¶
Adds the truncated value of ⟨expression⟩ to ⟨counter⟩.
-
\pgfmathsetmacro{⟨macro⟩}{⟨expression⟩} ¶
Defines ⟨macro⟩ as the value of ⟨expression⟩. The result is a decimal without units.
-
\pgfmathsetlengthmacro{⟨macro⟩}{⟨expression⟩} ¶
Defines ⟨macro⟩ as the value of ⟨expression⟩ in points.
-
\pgfmathtruncatemacro{⟨macro⟩}{⟨expression⟩} ¶
Defines ⟨macro⟩ as the truncated value of ⟨expression⟩.
94.1.2 Considerations Concerning Units¶
As was explained earlier, the parser commands like \pgfmathparse will always return a result without units in it and all dimensions that have a unit like 10pt or 1in will first be converted to TeX points (pt) and, then, the unit is dropped.
Sometimes it is useful, nevertheless, to find out whether an expression or not. For this, you can use the following commands:
-
\ifpgfmathunitsdeclared ¶
After a call of \pgfmathparse this if will be true exactly if some unit was encountered in the expression. It is always set globally in each call.
Note that any “mentioning” of a unit inside an expression will set this TeX-if to true. In particular, even an expressionlike 2pt/1pt, which arguably should be considered “scalar” or “unit-free” will still have this TeX-if set to true. However, see the scalar function for a way to change this.
-
scalar(value)
-
\pgfmathscalar{value} ¶
This function is the identity function on its input, but it will reset the TeX-if \ifpgfmathunitsdeclared. Thus, it can be used to indicate that the given ⟨value⟩ should be considered as a “scalar” even when it contains units; but note that it will work even when the ⟨value⟩ is a string or something else. The only effect of this function is to clear the unit declaration.
Note, however, that this command (currently) really just clears the TeX-if as the input is scanned from left-to-right. Thus, even if there is a use of a unit before the scalar function is used, the TeX-if will be cleared:
The other way round, a use of a unit after the scalar function will set the units once more.
For these reasons, you should use the function only on the outermost level of an expression.
A typical use of this function is the following:
A special kind of units are TeX’s “math units” (mu). It will be treated as if pt had been used, but you can check whether an expression contained a math unit using the following:
-
\ifpgfmathmathunitsdeclared ¶
This TeX-if is similar to \ifpgfmathunitsdeclared, but it is only set when the unit mu is encountered at least once. In this case, \ifpgfmathunitsdeclared will also be set to true. The scalar function has no effect on this TeX-if.
94.2 Syntax for Mathematical Expressions: Operators¶
The syntax for the expressions recognized by \pgfmathparse and friends is rather straightforward. Let us start with the operators.
The following operators (presented in the context in which they are used) are recognized:
-
x + y (infix operator; uses the add function)
Adds x to y.
-
x - y (infix operator; uses the subtract function)
Subtracts y from x.
-
-x (prefix operator; uses the neg function)
Reverses the sign of x.
-
x * y (infix operator; uses the multiply function)
Multiplies x by y.
-
x / y (infix operator; uses the divide function)
Divides x by y. An error will result if y is 0, or if the result of the division is too big for the mathematical engine. Please remember when using this command that accurate (and reasonably quick) division of real numbers that are not integers is particularly tricky in TeX.
-
x ^ y (infix operator; uses the pow function)
Raises x to the power y.
-
x! (postfix operator; uses the factorial function)
Calculates the factorial of x.
-
xr (postfix operator; uses the deg function)
Converts x to degrees (x is assumed to be in radians). This operator has the same precedence as multiplication.
-
x ? y : z (conditional operators; use the ifthenelse function)
? and : are special operators which can be used as a shorthand for if x then y else z inside the parser. The expression x is taken to be true if it evaluates to any non-zero value.
-
x == y (infix operator; uses the equal function)
Returns 1 if x\(=\)y, 0 otherwise.
-
x > y (infix operator; uses the greater function)
Returns 1 if x\(>\)y, 0 otherwise.
-
x < y (infix operator; uses the less function)
Returns 1 if x\(<\)y, 0 otherwise.
-
x != y (infix operator; uses the notequal function)
Returns 1 if x\(\neq \)y, 0 otherwise.
-
x >= y (infix operator; uses the notless function)
Returns 1 if x\(\geq \)y, 0 otherwise.
-
x <= y (infix operator; uses the notgreater function)
Returns 1 if x\(\leq \)y, 0 otherwise.
-
x && y (infix operator; uses the and function)
Returns 1 if both x and y evaluate to some non-zero value. Both arguments are evaluated.
-
x || y (infix operator; uses the or function)
Returns 1 if either x or y evaluate to some non-zero value.
-
!x (prefix operator; uses the not function)
Returns 1 if x evaluates to zero, 0 otherwise.
-
(x) (group operators)
These operators act in the usual way, that is, to control the order in which operators are executed, for example, (1+2)*3. This includes the grouping of arguments for functions, for example, sin(30*10) or mod(72,3) (the comma character is also treated as an operator).
Parentheses for functions with one argument are not always necessary, sin 30 (note the space) is the same as sin(30). However, functions have the highest precedence so, sin 30*10 is the same as sin(30)*10.
-
{x} (array operators)
These operators are used to process array-like structures (within an expression these characters do not act like TeX grouping tokens). The ⟨array specification⟩ consists of comma separated elements, for example, {1, 2, 3, 4, 5}. Each element in the array will be evaluated as it is parsed, so expressions can be used. In addition, an element of an array can be an array itself, allowing multiple dimension arrays to be simulated: {1, {2,3}, {4,5}, 6}. When storing an array in a macro, do not forget the surrounding braces: \def\myarray{{1,2,3}} not \def\myarray{1,2,3}.
-
[x] (array access operators; use the array function)
[ and ] are two operators used in one particular circumstance: to access an array (specified using the { and } operators) using the index x. Indexing starts from zero, so, if the index is greater than, or equal to, the number of values in the array, an error will occur, and zero will be returned.
If the array is defined to have multiple dimensions, then the array access operators can be immediately repeated.
-
"x" (group operators)
These operators are used to quote x. However, as every expression is expanded with \edef before it is parsed, macros (e.g., font commands like \tt or \Huge) may need to be “protected” from this expansion (e.g., \noexpand\Huge). Ideally, you should avoid such macros anyway. Obviously, these operators should be used with great care as further calculations are unlikely to be possible with the result.
94.3 Syntax for Mathematical Expressions: Functions¶
The following functions are recognized:
-
• abs, acos, add, and, array, asin, atan, atan2, bin, ceil, cos, cosec, cosh, cot, deg, depth, dim, div, divide, e, equal, factorial, false, floor, frac, gcd, greater, height, hex, Hex, int, ifthenelse, iseven, isodd, isprime, less, ln, log10, log2, max, min, mod, Mod, multiply, neg, not, notequal, notgreater, notless, oct, or, pi, pow, rad, rand, random, real, rnd, round, scalar, sec, sign, sin, sinh, sqrt, subtract, tan, tanh, true, veclen, width
Each function has a pgf command associated with it (which is also shown with the function below). In general, the command is simply the name of the function prefixed with \pgfmath, for example, \pgfmathadd, but there are some notable exceptions.
94.3.1 Basic arithmetic functions¶
-
add(x,y)
-
\pgfmathadd{x}{y} ¶
Adds \(x\) and \(y\).
-
subtract(x,y)
-
\pgfmathsubtract{x}{y} ¶
Subtract \(y\) from \(x\).
-
neg(x)
-
\pgfmathneg{x} ¶
This returns \(-x\).
-
multiply(x,y)
-
\pgfmathmultiply{x}{y} ¶
Multiply \(x\) by \(y\).
-
divide(x,y)
-
\pgfmathdivide{x}{y} ¶
Divide \(x\) by \(y\).
-
div(x,y)
-
\pgfmathdiv{x}{y} ¶
Divide \(x\) by \(y\) and return the integer part of the result.
-
factorial(x)
-
\pgfmathfactorial{x} ¶
Return x!.
-
sqrt(x)
-
\pgfmathsqrt{x} ¶
Calculates \(\sqrt {x}\).
-
pow(x,y)
-
\pgfmathpow{x}{y} ¶
Raises x to the power y. For greatest accuracy, y should be an integer. If y is not an integer, the actual calculation will be an approximation of \(e^{y \ln (x)}\).
-
e
-
\pgfmathe ¶
Returns the value 2.718281828.
-
exp(x)
-
\pgfmathexp{x} ¶
Maclaurin series for \(e^x\).
-
ln(x)
-
\pgfmathln{x} ¶
An approximation for \(\ln (x)\). This uses an algorithm of Rouben Rostamian, and coefficients suggested by Alain Matthes.
-
log10(x)
-
\pgfmathlogten{x} ¶
An approximation for \(\log _{10}(x)\).
-
log2(x)
-
\pgfmathlogtwo{x} ¶
An approximation for \(\log _2(x)\).
-
abs(x)
-
\pgfmathabs{x} ¶
Evaluates the absolute value of \(x\).
-
mod(x,y)
-
\pgfmathmod{x}{y} ¶
This evaluates x modulo y, using truncated division. The sign of the result is the same as the sign of \(\frac {x}{y}\).
-
Mod(x,y)
-
\pgfmathMod{x}{y} ¶
This evaluates x modulo y, using floored division. The sign of the result is never negative.
-
sign(x)
-
\pgfmathsign{x} ¶
Returns the sign of \(x\).
94.3.2 Rounding functions¶
-
round(x)
-
\pgfmathround{x} ¶
Rounds x to the nearest integer. It uses “asymmetric half-up” rounding. So 1.5 is rounded to 2, but -1.5 is rounded to -2 (not -1).
-
floor(x)
-
\pgfmathfloor{x} ¶
Rounds x down to the nearest integer.
-
ceil(x)
-
\pgfmathceil{x} ¶
Rounds x up to the nearest integer.
-
int(x)
-
\pgfmathint{x} ¶
Returns the integer part of x.
-
frac(x)
-
\pgfmathfrac{x} ¶
Returns the fractional part of x.
-
real(x)
-
\pgfmathreal{x} ¶
Ensures x contains a decimal point.
94.3.3 Integer arithmetic functions¶
-
gcd(x,y)
-
\pgfmathgcd{x}{y} ¶
Computes the greatest common divider of x and y.
-
isodd(x)
-
\pgfmathisodd{x} ¶
Returns 1 if the integer part of x is odd. Otherwise, returns 0.
-
iseven(x)
-
\pgfmathiseven{x} ¶
Returns 1 if the integer part of x is even. Otherwise, returns 0.
-
isprime(x)
-
\pgfmathisprime{x} ¶
Returns 1 if the integer part of x is prime. Otherwise, returns 0.
94.3.4 Trigonometric functions¶
-
pi
-
\pgfmathpi ¶
Returns the value \(\pi =3.141592654\).
-
rad(x)
-
\pgfmathrad{x} ¶
Convert x to radians. x is assumed to be in degrees.
-
deg(x)
-
\pgfmathdeg{x} ¶
Convert x to degrees. x is assumed to be in radians.
-
sin(x)
-
\pgfmathsin{x} ¶
Sine of x. By employing the r operator, x can be in radians.
-
cos(x)
-
\pgfmathcos{x} ¶
Cosine of x. By employing the r operator, x can be in radians.
-
tan(x)
-
\pgfmathtan{x} ¶
Tangent of x. By employing the r operator, x can be in radians.
-
sec(x)
-
\pgfmathsec{x} ¶
Secant of x. By employing the r operator, x can be in radians.
-
cosec(x)
-
\pgfmathcosec{x} ¶
Cosecant of x. By employing the r operator, x can be in radians.
-
cot(x)
-
\pgfmathcot{x} ¶
Cotangent of x. By employing the r operator, x can be in radians.
-
asin(x)
-
\pgfmathasin{x} ¶
Arcsine of x. The result is in degrees and in the range \(\pm 90^\circ \).
-
acos(x)
-
\pgfmathacos{x} ¶
Arccosine of x in degrees. The result is in the range \([0^\circ ,180^\circ ]\).
-
atan(x)
-
\pgfmathatan{x} ¶
Arctangent of \(x\) in degrees.
-
atan2(y,x)
-
\pgfmathatantwo{y}{x} ¶
Arctangent of \(y\div x\) in degrees. This also takes into account the quadrants.
-
/pgf/trig format=deg|rad (no default, initially deg) ¶
Allows to define whether trigonometric math functions (i.e. all in this subsection) operate with degrees or with radians.
The initial configuration trig format=deg is the base of pgf: almost all of it is based on degrees.
Specifying trig format=rad is most useful for data visualization where the angles are typically given in radians. However, it is applied to all trigonometric functions for which the option applies, including any drawing instructions which operate on angles.
Warning: At the time of this writing, this feature is “experimental”. Please handle it with care: there may be path instructions or libraries in pgf which rely on trig format=deg. The intended usage of trig format=rad is for local scopes – and as option for data visualization.
94.3.5 Comparison and logical functions¶
-
equal(x,y)
-
\pgfmathequal{x}{y} ¶
This returns 1 if \(x=y\) and 0 otherwise.
-
greater(x,y)
-
\pgfmathgreater{x}{y} ¶
This returns 1 if \(\mvar {x}>\mvar {y}\) and 0 otherwise.
-
less(x,y)
-
\pgfmathless{x}{y} ¶
This returns 1 if \(x<\mvar {y}\) and 0 otherwise.
-
notequal(x,y)
-
\pgfmathnotequal{x}{y} ¶
This returns 0 if \(x=\mvar {y}\) and 1 otherwise.
-
notgreater(x,y)
-
\pgfmathnotgreater{x}{y} ¶
This returns 1 if \(x\leq \mvar {y}\) and 0 otherwise.
-
notless(x,y)
-
\pgfmathnotless{x}{y} ¶
This returns 1 if \(x\geq \mvar {y}\) and 0 otherwise.
-
and(x,y)
-
\pgfmathand{x}{y} ¶
This returns 1 if x and y both evaluate to non-zero values. Otherwise 0 is returned.
-
or(x,y)
-
\pgfmathor{x}{y} ¶
This returns 1 if either x or y evaluate to non-zero values. Otherwise 0 is returned.
-
not(x)
-
\pgfmathnot{x} ¶
This returns 1 if \(\mvar {x}=0\), otherwise 0.
-
ifthenelse(x,y,z)
-
\pgfmathifthenelse{x}{y}{z} ¶
This returns y if x evaluates to some non-zero value, otherwise z is returned.
-
true
-
\pgfmathtrue ¶
This evaluates to 1.
-
false
-
\pgfmathfalse ¶
This evaluates to 0.
94.3.6 Pseudo-random functions¶
-
rnd
-
\pgfmathrnd ¶
Generates a pseudo-random number between \(0\) and \(1\) with a uniform distribution.
-
rand
-
\pgfmathrand ¶
Generates a pseudo-random number between \(-1\) and \(1\) with a uniform distribution.
-
random(x,y)
-
\pgfmathrandom{x,y} ¶
This function takes zero, one or two arguments. If there are zero arguments, a uniform random number between \(0\) and \(1\) is generated. If there is one argument x, a random integer between \(1\) and x is generated. Finally, if there are two arguments, a random integer between x and y is generated. If there are no arguments, the pgf command should be called as follows: \pgfmathrandom{}.
94.3.7 Base conversion functions¶
-
hex(x)
-
\pgfmathhex{x} ¶
Convert x (assumed to be an integer in base 10) to a hexadecimal representation, using lower case alphabetic digits. No further calculation will be possible with the result.
-
Hex(x)
-
\pgfmathHex{x} ¶
Convert x (assumed to be an integer in base 10) to a hexadecimal representation, using upper case alphabetic digits. No further calculation will be possible with the result.
-
oct(x)
-
\pgfmathoct{x} ¶
Convert x (assumed to be an integer in base 10) to an octal representation. No further calculation should be attempted with the result, as the parser can only process numbers converted to base 10.
-
bin(x)
-
\pgfmathbin{x} ¶
Convert x (assumed to be an integer in base 10) to a binary representation. No further calculation should be attempted with the result, as the parser can only process numbers converted to base 10.
94.3.8 Miscellaneous functions¶
-
min(x\(_1\),x\(_2\),…,x\(_n\))
-
\pgfmathmin{x\(_1\),x\(_2\),…}{…,x\(_{n-1}\),x\(_n\)} ¶
Return the minimum value from x\(_1\)…x\(_n\). For historical reasons, the command \pgfmathmin takes two arguments, but each of these can contain an arbitrary number of comma separated values.
-
max(x\(_1\),x\(_2\),…,x\(_n\))
-
\pgfmathmax{x\(_1\),x\(_2\),…}{…,x\(_{n-1}\),x\(_n\)} ¶
Return the maximum value from x\(_1\)…x\(_n\). Again, for historical reasons, the command \pgfmathmax takes two arguments, but each of these can contain an arbitrary number of comma separated values.
-
veclen(x,y)
-
\pgfmathveclen{x}{y} ¶
Calculates \(\sqrt {\left (\mvar {x}^2+\mvar {y}^2\right )}\). This uses a polynomial approximation, based on ideas of Rouben Rostamian
-
array(x,y)
-
\pgfmatharray{x}{y} ¶
This accesses the array x at the index y. The array must begin and end with braces (e.g., {1,2,3,4}) and array indexing starts at 0.
-
dim(x)
-
\pgfmathdim{x} ¶
This returns the dimension of the array x. The array must begin and end with braces (e.g., {1,2,3,4}).
The following hyperbolic functions were adapted from code suggested by Martin Heller:
-
sinh(x)
-
\pgfmathsinh{x} ¶
The hyperbolic sine of x
-
cosh(x)
-
\pgfmathcosh{x} ¶
The hyperbolic cosine of x
-
tanh(x)
-
\pgfmathtanh{x} ¶
The hyperbolic tangent of x
-
width("x")
-
\pgfmathwidth{"x"} ¶
Return the width of a TeX (horizontal) box containing x. The quote characters are necessary to prevent x from being parsed. It is important to remember that any expression is expanded with \edef before being parsed, so any macros (e.g., font commands like \tt or \Huge) will need to be “protected” (e.g., \noexpand\Huge is usually sufficient).
Note that results of this method are provided in points.
-
height("x")
-
\pgfmathheight{"x"} ¶
Return the height of a box containing x.
-
depth("x")
-
\pgfmathdepth{"x"} ¶
Returns the depth of a box containing x.