Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

Is there a specific reason that there is no default macro (e.g. \pgfmath{<expression>}) that directly expands to the result of the evaluated <expression>? It always strikes me as particularly cumbersome when I have to type \pgfmathparse{\linewidth-2.7cm}\pgfmathresult just to calculate some length that's only used once.

Since such macros would come quite handy for single-use calculations I tried to define my own, but to no avail. Can you help me out with these definitions or at least expain why such a thing is not possible?

What bothers me is the fact that both my \pgflength and the default \pgfmathresult are just macros (according to \show) and both ultimately expand to a sequence of numbers. :-(

\documentclass{article}

\usepackage{pgf}

\newcommand\pgfmath[1]{\pgfmathparse{#1}\pgfmathresult}
\newcommand\pgftrunc[1]{\pgfmathparse{int(#1)}\pgfmathresult}
\newcommand\pgflength[1]{\pgfmathparse{#1}\pgfmathresult pt}

\begin{document}
% Fails:
%\hspace{\pgflength{1cm+2cm}}

% Error message:
% ! Missing number, treated as zero.
% <to be read again> 
%                  \begingroup 
% l.14     \hspace{\pgflength{1cm+2cm}}

% Works:
\pgfmathparse{1cm+2cm}
\hspace{\pgfmathresult pt}

% Curiously this also fails:
%\edef\mylength{\pgflength{1cm+2cm}}

% Error message:
% ! Incomplete \iffalse; all text was ignored after line 24.
% <inserted text> 
%                 \fi 

\end{document}
share|improve this question

1 Answer 1

up vote 12 down vote accepted

\pgfmath is not expandable, and so has to be used with a 'known' output macro to provide the result (for more on expandable code, see for example Tricks to make macros expandable and Why isn't everything expandable?). The LaTeX3 FPU is expandable, and so you can do

\documentclass{article}

\usepackage{expl3}
\ExplSyntaxOn
\newcommand{\fpmath}[1]{\fp_eval:n{#1}}
\newcommand{\fptrunc}[1]{\fp_to_int:n{#1}}
\newcommand{\fplength}[1]{\fp_eval:n{#1}~pt~}
\ExplSyntaxOff

\begin{document}
\hspace{\fplength{1cm+2cm}}

\edef\mylength{\fplength{1cm+2cm}}

\end{document}

The LaTeX3 FPU currently does not have the same coverage as the pgfmath code, and so things will never be possible in an expandable way (for example measuring material typeset into boxes). The expandable FPU is also slower than non-expandable code in many cases (here roughly twice as long is needed for the calculation, although the precision is higher).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.