3

I'd like to add two tikz dimensions, like so

\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
    \newdimen\heya
    \newdimen\xtra
    \xtra=0.3cm
    \heya=4cm+\xtra
    \draw (0,0) -- (\heya, 0);
\end{tikzpicture}
\end{document}

The line \heya=4cm+\xtra causes an error. What's the right way to do this?

Thanks!

=======

UPDATE: See Steven's answer below.

I found it easier to create a macro, à la

\newcommand{\add}[2]{\dimexpr#1+#2\relax}

and then...

\heya=\add{4cm}{\xtra}

...works as desired!

Labrador
  • 245

1 Answers1

5

Nothing to do with tikz but the TeX primitive \dimexpr (terminated by a unexpandable token such as \relax) allows dimensional math calculations.

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
    \newdimen\heya
    \newdimen\xtra
    \xtra=0.3cm
    \heya=\dimexpr4cm+\xtra\relax
    \draw (0,0) -- (\heya, 0);
\end{tikzpicture}
\end{document}
\end{document}

Within tikz, calculations can be done in braces, such as {\xtra+4cm}. As Torbjørn T. points out, the braces are optional if the argument has no parentheses, but it may be just easier to place them there to avoid the risk of a future edit.

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
    \newdimen\heya
    \newdimen\xtra
    \xtra=0.3cm
    \draw (0,0) -- ({\xtra+4cm}, 0);
\end{tikzpicture}
\end{document}

enter image description here

  • 1
    Strictly speaking the braces in your last example aren't needed, but they are required if the expression contains parentheses, e.g. ({sin(90)},0). – Torbjørn T. Nov 03 '17 at 19:55
  • Thanks, that worked. I created a macro \add{#1}{#2} for \dimexpr#1+#2\relax which should make it even easier on my brain in future... – Labrador Nov 03 '17 at 20:11
  • @Labrador You just have to be careful when using \defed variables instead of length variables, if negatives are involved: -\dimexpr-2cm\relax is 2cm, but --2cm is not. – Steven B. Segletes Nov 03 '17 at 20:16
  • technically it's ε-TeX primitive – user202729 Aug 10 '22 at 10:24