# pgfmath does not work

I want to use the pgfmath engine, but the result is not what I expect. In this example, I want both lines to have the same length.

\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfmath}
\begin{document}
\begin{tikzpicture}
\draw[color=blue, very thick] (0,0) -- (2,0);
\pgfmathparse{ceil(1.7)} % Why is the red line shorter? It should be 2 units in length
\draw[color=red, very thick] (0,0.5) -- (\pgfmathresult,0.5);
\end{tikzpicture}
\end{document}


Sorry if this question seems too stupid, but I don't know what's wrong. Thanks for your help.

• have you tried {\pgfmathresult}? – daleif Jun 27 at 10:55
• @daleif This is not the problem here, it's just that \pgfmathresult was getting overwitten. – frougon Jun 27 at 11:07
• Use \pgfmathsetmacro\myceil{ceil(1.7)} and then \myceil instead of \pgfmathresult. – Henri Menke Jun 27 at 11:11
• I know it's not how TikZ/PGF works (or LateX in general for that matter) but it would be more intuitive if there was a more clear concept of user namespace/context, in this case that \pgfmathresult contains the most recent result of what the user computed in their code, and not the most recent result of whatever TikZ has been doing in the background. – Marijn Jun 27 at 11:38
• @Marijn PGF/TikZ is accepting pull requests: github.com/pgf-tikz/pgf – Henri Menke Jun 27 at 23:49

PGF is used everywhere in TikZ. At the point where you invoke \pgfmathresult, the result of your calculation has already been overwritten by something from the last \draw statement before the point where you used \pgfmathresult.

In order to avoid this problem, you can store the the result right after computing it:

\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\draw[color=blue, very thick] (0,0) -- (2,0);
\pgfmathparse{ceil(1.7)}
\let\mylen\pgfmathresult
% This would also work, but \let means less work to do
% for TeX (thanks to egreg for the suggestion!)
% \edef\mylen{\pgfmathresult}
\draw[color=red, very thick] (0,0.5) -- (\mylen,0.5);
\end{tikzpicture}
\end{document}


but there is a shortcut for this, which is to use \pgfmathsetmacro:

\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\draw[color=blue, very thick] (0,0) -- (2,0);
\pgfmathsetmacro{\mylen}{ceil(1.7)}
\draw[color=red, very thick] (0,0.5) -- (\mylen,0.5);
\end{tikzpicture}
\end{document}


• Simpler would be \let\mylen\pgfmathresult, but \pgfmathsetmacro is conceptually better. – egreg Jun 27 at 14:08
• @egreg Indeed you're right, I've put the \let technique instead of the \edef. Thanks! – frougon Jun 27 at 14:13