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
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With