如何在LaTeX / TikZ中执行“复杂”计算

Tha*_*gon 5 latex tikz

我希望这个问题已经被回答了上千次,但是我只是无法找到解决问题的方法=(

我想在LaTeX(TikZ)中计算一些值,其中一些是长度(例如10 pt),有些则不是。只要计算形式非常简单,就像a*b+c一切都很好,但是如果我需要像(a+b)*(c+d)LaTeX 这样的括号,就会抱怨。此外,如果我有嵌套定义,则无法按预期解决这些问题。例:

\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
Run Code Online (Sandbox Code Playgroud)

所以基本上我的问题是:在LaTeX中进行计算的正确(或推荐)方法是什么?

作为一个更现实的示例,这是我实际上想要做的,但不能做的:

% 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
Run Code Online (Sandbox Code Playgroud)

不幸的是,由于将变量用于各种计算,因此我无法将\ numnodes重新定义为6。

最好的祝福

pch*_*gno 6

您可以\pgfmathsetmacro用于更复杂的计算。不过,您需要移除该单元myheight

% 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)}
Run Code Online (Sandbox Code Playgroud)

您可以在使用时重新添加该单元: \draw (0,0) -- ({\heightpernodeA ex},{1});

  • `\pgfmathsetmacro` 可以用于像 `20 * (12 + 762)` 这样的原始计算,但是如果你尝试使用单位(长度)来计算,你会遇到麻烦。唯一的解决方法是在使用像 `\mymacro{}pt` 这样的宏时附加长度。`\pgfmathsetlengthmacro` 专门设计用于处理长度,因此您可以执行类似 `20 * (12pt + 762cm)` 的操作。在内部,每个长度值都转换为 pt。因此,您总能得到正确的长度,甚至在使用宏时不必附加单位。 (2认同)