PGF/TikZ Manual

# The TikZ and PGF Packages Manual for version 3.1.10

## Libraries

#### 56Floating Point Unit Library

by Christian Feuersänger

• TikZ Library fpu

• \usepgflibrary{fpu} % and plain and pure pgf
\usepgflibrary[fpu] % Cont and pure pgf
\usetikzlibrary{fpu} % and plain when using TikZ
\usetikzlibrary[fpu] % Cont when using TikZ

The floating point unit (fpu) allows the full data range of scientific computing for use in pgf. Its core is the pgf math routines for mantissa operations, leading to a reasonable trade-off between speed and accuracy. It does not require any third-party packages or external programs.

##### 56.1Overview¶

The fpu provides a replacement set of math commands which can be installed in isolated placed to achieve large data ranges at reasonable accuracy. It provides at least10the IEEE double precision data range, $$-1 \cdot 10^{324}, \dotsc , 1\cdot 10^{324}$$. The absolute smallest number bigger than zero is $$1 \cdot 10^{-324}$$. The FPU’s relative precision is at least $$1 \cdot 10^{-4}$$ although operations like addition have a relative precision of $$1 \cdot 10^{-6}$$.

Note that the library has not really been tested together with any drawing operations. It should be used to work with arbitrary input data which is then transformed somehow into pgf precision. This, in turn, can be processed by pgf.

10 To be more precise, the FPU’s exponent is currently a 32-bit integer. That means it supports a significantly larger data range than an IEEE double precision number – but if a future version may provide low-level access to doubles, this may change.

##### 56.2Usage¶
• /pgf/fpu={boolean} (default true)

• This key installs or uninstalls the FPU. The installation exchanges any routines of the standard math parser with those of the FPU: \pgfmathadd will be replaced with \pgfmathfloatadd and so on. Furthermore, any number will be parsed with \pgfmathfloatparsenumber.

The FPU uses a low-level number representation consisting of flags, mantissa and exponent11.To avoid unnecessary format conversions, \pgfmathresult will usually contain such a cryptic number. Depending on the context, the result may need to be converted into something which is suitable for pgf processing (like coordinates) or may need to be typeset. The FPU provides such methods as well.

Use fpu=false to deactivate the FPU. This will restore any change. Please note that this is not necessary if the FPU is used inside of a group – it will be deactivated afterwards anyway.

It does not hurt to call fpu=true or fpu=false multiple times.

Please note that if the fixedpointarithmetic library of pgf will be activated after the FPU, the FPU will be deactivated automatically.

• /pgf/fpu/output format=float|sci|fixed (no default, initially float)

• This key allows to change the number format in which the FPU assigns \pgfmathresult.

The predefined choice float uses the low-level format used by the FPU. This is useful for further processing inside of any library.

The choice sci returns numbers in the format mantissaeexponent. It provides almost no computational overhead.

The choice fixed returns normal fixed point numbers and provides the highest compatibility with the pgf engine. It is activated automatically in case the FPU scales results.

• /pgf/fpu/scale results={scale}(no default)

• A feature which allows semi-automatic result scaling. Setting this key has two effects: first, the output format for any computation will be set to fixed (assuming results will be processed by pgf’s kernel). Second, any expression which starts with a star, *, will be multiplied with scale.

• /pgf/fpu/scale file plot x={scale}(no default)

• /pgf/fpu/scale file plot y={scale}(no default)

• /pgf/fpu/scale file plot z={scale}(no default)

• These keys will patch pgf’s plot file command to automatically scale single coordinates by scale.

The initial setting does not scale plot file.

• \pgflibraryfpuifactive{true-code}{false-code}

• This command can be used to execute either true-code or false-code, depending on whether the FPU has been activated or not.

• /pgf/fpu/install only={list of names}(no default)

• Unfortunately, the FPU is currently incompatible with drawing operations. However, it can still be useful to replace single definitions with FPU counterparts to avoid errors of the kind Dimension too large which tend to happen when transformation matrices are inverted.

This key allows to specify a list of definitions to be pulled into the current scope. Note that there is no reverse operation to uninstall these definitions at the moment, so it is advisable to do this in a group. Conveniently, TikZ paths form an implicit group, so you can use this key on a path as well.

You have to be aware of the limitations that the FPU imposes. It will not magically give better precision, but it will avoid overflow or underflow situations for large or small operands by rescaling them. In the following example, in the first case the FPU variant performs much better than the normal variant, however, in the second case where a rescaling would not in fact be needed the rescaling introduces a small round-off error.

This key is introduced in pgfv3.1.6 and marked stable since pgfv3.1.8.

11 Users should always use high level routines to manipulate floating point numbers as the format may change in a future release.

##### 56.3Comparison to the fixed point arithmetics library¶

There are other ways to increase the data range and/or the precision of pgf’s math parser. One of them is the fp package, preferable combined with pgf’s fixedpointarithmetic library. The differences between the FPU and fp are:

• • The FPU supports at least the complete IEEE double precision number range, while fp covers only numbers of magnitude $$\pm 1\cdot 10^{17}$$.

• • The FPU has a uniform relative precision of about 4–5 correct digits. The fixed point library has an absolute precision which may perform good in many cases – but will fail at the ends of the data range (as every fixed point routines does).

• • The FPU has potential to be faster than fp as it has access to fast mantissa operations using pgf’s math capabilities (which use registers).

##### 56.4Command Reference and Programmer’s Manual¶
###### 56.4.1Creating and Converting Floats¶
• \pgfmathfloatparsenumber{x}

• Reads a number of arbitrary magnitude and precision and stores its result into \pgfmathresult as floating point number $$m \cdot 10^e$$ with mantissa and exponent base $$10$$.

The algorithm and the storage format is purely text-based. The number is stored as a triple of flags, a positive mantissa and an exponent, such as

Please do not rely on the low-level representation here, use \pgfmathfloattomacro (and its variants) and \pgfmathfloatcreate if you want to work with these components.

The flags encoded in \pgfmathresult are represented as a digit where ‘$$0$$’ stands for the number $$\pm 0\cdot 10^0$$, ‘$$1$$’ stands for a positive sign, ‘$$2$$’ means a negative sign, ‘$$3$$’ stands for ‘not a number’, ‘$$4$$’ means $$+\infty$$ and ‘$$5$$’ stands for $$-\infty$$.

The mantissa is a normalized real number $$m \in \mathbb {R}$$, $$1 \le m < 10$$. It always contains a period and at least one digit after the period. The exponent is an integer.

Examples:

The argument x may be given in fixed point format or the scientific “e” (or “E”) notation. The scientific notation does not necessarily need to be normalized. The supported exponent range is (currently) only limited by the -integer range (which uses 31 bit integer numbers).

• /pgf/fpu/handlers/empty number={input}{unreadable part}(no default)

• This command key is invoked in case an empty string is parsed inside of \pgfmathfloatparsenumber. You can overwrite it to assign a replacement \pgfmathresult (in float!).

The initial setting is to invoke invalid number, see below.

• /pgf/fpu/handlers/invalid number={input}{unreadable part}(no default)

• This command key is invoked in case an invalid string is parsed inside of \pgfmathfloatparsenumber. You can overwrite it to assign a replacement \pgfmathresult (in float!).

The initial setting is to generate an error message.

• /pgf/fpu/handlers/wrong lowlevel format={input}{unreadable part}(no default)

• This command key is invoked whenever \pgfmathfloattoregisters or its variants encounter something which is not a properly formatted low-level floating point number. As for invalid number, this key may assign a new \pgfmathresult (in floating point) which will be used instead of the offending input.

The initial setting is to generate an error message.

• \pgfmathfloatqparsenumber{x}

• The same as \pgfmathfloatparsenumber, but does not perform sanity checking.

• \pgfmathfloattofixed{x}

• Converts a number in floating point representation to a fixed point number. It is a counterpart to \pgfmathfloatparsenumber. The algorithm is purely text based and defines \pgfmathresult as a string sequence which represents the floating point number x as a fixed point number (of arbitrary precision).

• \pgfmathfloattoint{x}

• Converts a number from low-level floating point representation to an integer (by truncating the fractional part).

See also \pgfmathfloatint which returns the result as float.

• \pgfmathfloattosci{float}

• Converts a number from low-level floating point representation to scientific format, $$1.234e4$$. The result will be assigned to the macro \pgfmathresult.

• \pgfmathfloatvalueof{float}

• Expands a number from low-level floating point representation to scientific format, $$1.234e4$$.

Use \pgfmathfloatvalueof in contexts where only expandable macros are allowed.

• \pgfmathfloatcreate{flags}{mantissa}{exponent}

• Defines \pgfmathresult as the floating point number encoded by flags, mantissa and exponent.

All arguments are characters and will be expanded using \edef.

• \pgfmathfloatifflags{floating point number}{flag}{true-code}{false-code}

• Invokes true-code if the flag of floating point number equals flag and false-code otherwise.

The argument flag can be one of

0

to test for zero,

1

to test for positive numbers,

+

to test for positive numbers,

2

to test for negative numbers,

-

to test for negative numbers,

3

for “not-a-number”,

4

for $$+\infty$$,

5

for $$-\infty$$.

• \pgfmathfloattomacro{x}{flagsmacro}{mantissamacro}{exponentmacro}

• Extracts the flags of a floating point number x to flagsmacro, the mantissa to mantissamacro and the exponent to exponentmacro.

• Takes a floating point number x as input and writes flags to count register flagscount, mantissa to dimen register mantissadimen and exponent to count register exponentcount.

Please note that this method rounds the mantissa to -precision.

• \pgfmathfloattoregisterstok{x}{flagscount}{mantissatoks}{exponentcount}

• A variant of \pgfmathfloattoregisters which writes the mantissa into a token register. It maintains the full input precision.

• \pgfmathfloatgetflags{x}{flagscount}

• Extracts the flags of x into the count register flagscount.

• \pgfmathfloatgetflagstomacro{x}{macro}

• Extracts the flags of x into the macro macro.

• Extracts the mantissa of x into the dimen register mantissadimen.

• \pgfmathfloatgetmantissatok{x}{mantissatoks}

• Extracts the mantissa of x into the token register mantissatoks.

• \pgfmathfloatgetexponent{x}{exponentcount}

• Extracts the exponent of x into the count register exponentcount.

###### 56.4.2Symbolic Rounding Operations¶

Commands in this section constitute the basic level implementations of the rounding routines. They work symbolically, i.e. they operate on text, not on numbers and allow arbitrarily large numbers.

• \pgfmathroundto{x}

• Rounds a fixed point number to prescribed precision and writes the result to \pgfmathresult.

The desired precision can be configured with /pgf/number format/precision, see section 97. This section does also contain application examples.

Any trailing zeros after the period are discarded. The algorithm is purely text based and allows to deal with precisions beyond ’s fixed point support.

As a side effect, the global boolean \ifpgfmathfloatroundhasperiod will be set to true if and only if the resulting mantissa has a period. Furthermore, \ifpgfmathfloatroundmayneedrenormalize will be set to true if and only if the rounding result’s floating point representation would have a larger exponent than x.

• \pgfmathroundtozerofill{x}

• A variant of \pgfmathroundto which always uses a fixed number of digits behind the period. It fills missing digits with zeros.

• \pgfmathfloatround{x}

• Rounds a normalized floating point number to a prescribed precision and writes the result to \pgfmathresult.

The desired precision can be configured with /pgf/number format/precision, see section 97.

This method employs \pgfmathroundto to round the mantissa and applies renormalization if necessary.

As a side effect, the global boolean \ifpgfmathfloatroundhasperiod will be set to true if and only if the resulting mantissa has a period.

• \pgfmathfloatroundzerofill{x}

• A variant of \pgfmathfloatround produces always the same number of digits after the period (it includes zeros if necessary).

###### 56.4.3Math Operations Commands¶

This section describes some of the replacement commands in more detail.

Please note that these commands can be used even if the fpu as such has not been activated – it is sufficient to load the library.

• \pgfmathfloatop

• Methods of this form constitute the replacement operations where op can be any of the well-known math operations.

Thus, \pgfmathfloatadd is the counterpart for \pgfmathadd and so on. The semantics and number of arguments is the same, but all input and output arguments are expected to be floating point numbers.

• \pgfmathfloattoextentedprecision{x}

• Renormalizes x to extended precision mantissa, meaning $$100 \le m < 1000$$ instead of $$1 \le m < 10$$.

The “extended precision” means we have higher accuracy when we apply pgfmath operations to mantissas.

The input argument is expected to be a normalized floating point number; the output argument is a non-normalized floating point number (well, normalized to extended precision).

The operation is supposed to be very fast.

• \pgfmathfloatsetextprecision{shift}

• Sets the precision used inside of \pgfmathfloattoextentedprecision to shift.

The different choices are

.
0 normalization to $$0$$ $$\le m < 1$$ (disable extended precision)
1 normalization to $$10$$ $$\le m < 100$$
2 normalization to $$100$$ $$\le m < 1000$$ (default of \pgfmathfloattoextentedprecision)
3 normalization to $$1000$$ $$\le m < 10000$$
• \pgfmathfloatlessthan{x}{y}

• Defines \pgfmathresult as $$1.0$$ if $$\meta {x} < \meta {y}$$, but $$0.0$$ otherwise. It also sets the global -boolean \pgfmathfloatcomparison accordingly. The arguments x and y are expected to be numbers which have already been processed by \pgfmathfloatparsenumber. Arithmetic is carried out using -registers for exponent- and mantissa comparison.

• \pgfmathfloatmultiplyfixed{float}{fixed}

• Defines \pgfmathresult to be $$\meta {float} \cdot \meta {fixed}$$ where float is a floating point number and fixed is a fixed point number. The computation is performed in floating point arithmetics, that means we compute $$m \cdot \meta {fixed}$$ and renormalize the result where $$m$$ is the mantissa of float.

This operation renormalizes float with \pgfmathfloattoextentedprecision before the operation, that means it is intended for relatively small arguments of fixed. The result is a floating point number.

• \pgfmathfloatifapproxequalrel{a}{b}{true-code}{false-code}

• Computes the relative error between a and b (assuming b$$\neq 0$$) and invokes true-code if the relative error is below /pgf/fpu/rel thresh and false-code if that is not the case.

The input arguments will be parsed with \pgfmathfloatparsenumber.

• /pgf/fpu/rel thresh={number} (no default, initially 1e-4)

• A threshold used by \pgfmathfloatifapproxequalrel to decide whether numbers are approximately equal.

• \pgfmathfloatshift{x}{num}

• Defines \pgfmathresult to be $$\meta {x} \cdot 10^{\meta {num}}$$. The operation is an arithmetic shift base ten and modifies only the exponent of x. The argument num is expected to be a (positive or negative) integer.

• \pgfmathfloatabserror{x}{y}

• Defines \pgfmathresult to be the absolute error between two floating point numbers $$x$$ and $$y$$, $$\lvert x - y\rvert$$ and returns the result as floating point number.

• \pgfmathfloatrelerror{x}{y}

• Defines \pgfmathresult to be the relative error between two floating point numbers $$x$$ and $$y$$, $$\lvert x - y\rvert / \lvert y \rvert$$ and returns the result as floating point number.

• \pgfmathfloatint{x}

• Returns the integer part of the floating point number x, by truncating any digits after the period. This methods truncates the absolute value $$\rvert x \lvert$$ to the next smaller integer and restores the original sign afterwards.

The result is returned as floating point number as well.

See also \pgfmathfloattoint which returns the number in integer format.

• \pgfmathlog{x}

• Defines \pgfmathresult to be the natural logarithm of x, $$\ln (\meta {x})$$. This method is logically the same as \pgfmathln, but it applies floating point arithmetics to read number x and employs the logarithm identity

$\ln (m \cdot 10^e) = \ln (m) + e \cdot \ln (10)$

to get the result. The factor $$\ln (10)$$ is a constant, so only $$\ln (m)$$ with $$1 \le m < 10$$ needs to be computed. This is done using standard pgf math operations.

Please note that x needs to be a number, expression parsing is not possible here.

If x is not a bounded positive real number (for example $$\meta {x} \le 0$$), \pgfmathresult will be empty, no error message will be generated.

###### 56.4.4Accessing the Original Math Routines for Programmers¶

As soon as the library is loaded, every private math routine will be copied to a new name. This allows library and package authors to access the -register based math routines even if the FPU is activated. And, of course, it allows the FPU as such to perform its own mantissa computations.

The private implementations of pgf math commands, which are of the form \pgfmathname@, will be available as\pgfmath@basic@name@ as soon as the library is loaded.