11

I expect this question has already been answered a thousand times, but I just cannot find a solution to my issue =(

I want to calculate some values in LaTeX (TikZ), some of which are lengths (e.g. 10 pt), some are not. As long as calculations are of very simple forms like a*b+c everything is fine, but if I need brackets like (a+b)*(c+d) LaTeX complains. Furthermore, if I have nested definitions, these are not solved as expected. Example:

\def\varA{1+2}
\def\varB{10}
% I want to calculate (1+2)*10 or 10*(1+2), respectively.
\def\varC{\varA*\varB} % evaluates to 21
\def\varD{\varB*\varA} % evaluates to 12

So basically my question is: What is the correct (or recommended) way to do calculations in LaTeX?

As a more realistic example, here is something I actually want to do and just can't:

% total height of my TikZ image
\def\myheight{20ex}
% five nodes shall be drawn as a stack
\def\numnodes{5}
% but there shall be some space at the top (like a 6th node)
\def\heightpernodeA{\myheight / (\numnodes + 1)} % fails whenever I want to use it
% workaround?
\def\numnodesplusone{\numnodes + 1}
\def\heightpernodeB{\myheight / \numnodesplusone} % fails for the reason explained above

Unfortunately I can not redefine \numnodes to be 6 as I use the variable for various calculations.

best regards

Thargon
  • 424
  • 1
  • 3
  • 12

1 Answers1

6

You can use \pgfmathsetmacro for more complex calculation. You'll need to remove the unit in myheight though:

% total height of my TikZ image
\def\myheight{20}
% five nodes shall be drawn as a stack
\def\numnodes{5}
% but there shall be some space at the top (like a 6th node)
\pgfmathsetmacro\heightpernodeA{\myheight / (\numnodes + 1)}

You can add the unit back when you use it: \draw (0,0) -- ({\heightpernodeA ex},{1});

pchaigno
  • 11,313
  • 2
  • 29
  • 54
  • 1
    This definitely pointed to the right direction. I ended up using `\pgfmathsetlengthmacro` for my stuff. – Thargon Jan 31 '18 at 16:34
  • I don't know that one. What's the difference with `\pgfmathsetmacro`? – pchaigno Jan 31 '18 at 22:58
  • 3
    `\pgfmathsetmacro` can be used for raw calculations like `20 * (12 + 762)`, but you get in trouble if you try to use units (lengths) with this one. The only workaround is to append the length when using the macro like `\mymacro{}pt`. `\pgfmathsetlengthmacro` is specifically designed to work with lengths, so you can do something like `20 * (12pt + 762cm)`. Internally every length value is transformed to pt. As a result, you always get the correct length and you even don't have to append the unit when using the macro. – Thargon Mar 21 '18 at 13:44