7

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.

5
  • have you tried {\pgfmathresult}?
    – daleif
    Commented Jun 27, 2019 at 10:55
  • 1
    @daleif This is not the problem here, it's just that \pgfmathresult was getting overwitten.
    – frougon
    Commented Jun 27, 2019 at 11:07
  • 1
    Use \pgfmathsetmacro\myceil{ceil(1.7)} and then \myceil instead of \pgfmathresult. Commented Jun 27, 2019 at 11:11
  • 1
    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
    Commented Jun 27, 2019 at 11:38
  • @Marijn PGF/TikZ is accepting pull requests: github.com/pgf-tikz/pgf Commented Jun 27, 2019 at 23:49

1 Answer 1

18

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}

Screenshot

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .