我一直在尝试生成一个图,其中两个顶点以概率 p 连接。以下是我到目前为止尝试过的,
\pgfmathsetseed{\number\pdfrandomseed}
\begin{tikzpicture}
% size of circle
\def \radius {2cm}
\def \margin {8}
% number of vertices
\def \n {5}
% Probability for an edge to show up between vertices
\def \p {0.5}
% Drawing the vertices/nodes
\foreach \s in {1,...,\n}
\node[draw, circle] (\s) at ({360/\n * (\s - 1)}:\radius) {};
% Drawing the edges
\foreach \s in {1,...,\n}
\foreach \t in {\s,...,\n}
% Generate and store a random number to the variable \dummynum
\pgfmathparse{rnd}
\pgfmathsetmacro{\dummynum}{\pgfmathresult}
% If dummynum is less than p, edge is drawn; otherwise nothing happens
\ifthenelse{\lengthtest{\dummynum pt < \p pt}}{\draw (\t) -- (\s);}{}
\end{tikzpicture}
编译器无法编译它,并给出错误“段落在 \pgffor@next 完成之前结束”。
我确信问题出在 ifthenelse 行,但到目前为止我还不知道如何修复它。有人能指出错误并知道如何修复吗?谢谢。
答案1
我更喜欢使用 \ifdim ...\fi(tikz 解析器可以识别),而不是处理包\ifthenelse
中的宏。还有,但这需要使用我的编辑器自动转换为“...”(它的一个不太有用的功能)。此外,要求执行的代码位于组内。最后,我不知道你想用 做什么。 xifthen
\pgfmathifthenelse
"..."
\foreach
{...}
\pgfmathsetseed
\documentclass[]{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
% size of circle
\def \radius {2cm}
\def \margin {8}
% number of vertices
\def \n {5}
% Probability for an edge to show up between vertices
\def \p {0.5}
% Drawing the vertices/nodes
\foreach \s in {1,...,\n}
\node[draw, circle] (\s) at ({360/\n * (\s - 1)}:\radius) {};
% Drawing the edges
\foreach \s in {1,...,\n}{
\foreach \t in {\s,...,\n} {
% Generate and store a random number to the variable \dummynum
\pgfmathparse{rnd}
%\let\dummynum=\pgfmathresult
% If dummynum is less than p, edge is drawn; otherwise nothing happens
\ifdim\pgfmathresult pt < \p pt\relax \draw (\t) -- (\s);\fi
}}
\end{tikzpicture}
\end{document}