stern-brocot-tree.tex 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. \documentclass[tikz]{standalone}
  2. \usepackage{forest}
  3. \makeatletter
  4. \pgfmathdeclarefunction{strrepeat}{2}{%
  5. \begingroup
  6. \pgfmathint{#2}\pgfmath@count\pgfmathresult
  7. \let\pgfmathresult\pgfutil@empty
  8. \pgfutil@loop
  9. \ifnum\pgfmath@count>0\relax
  10. \expandafter\def\expandafter\pgfmathresult\expandafter{\pgfmathresult#1}%
  11. \advance\pgfmath@count-1\relax
  12. \pgfutil@repeat
  13. \pgfmath@smuggleone\pgfmathresult
  14. \endgroup}
  15. \makeatother
  16. \tikzset{
  17. Stern Brocot at/.style={at/.pgfmath={
  18. strcat("([rotate around=180:(!", strrepeat("#1",\SBLevel),")] !",
  19. strrepeat("#1",\SBLevel-1),"2)")}},
  20. Stern Brocot at*/.style n args={3}{
  21. at/.pgfmath={strcat("(!",strrepeat("#1",#2),"-| SB@#3)")},
  22. append after command/.expanded={\ifnum#2<\SBLevel(\noexpand\tikzlastnode)
  23. edge[densely dotted] (SB@#3@\the\numexpr\SBLLoop+1\relax)\fi}}}
  24. \begin{document}
  25. \begin{forest}
  26. Stern Brocot*/.style n args={2}{
  27. content=$\frac{#1}{#2}$,
  28. edge=densely dotted,
  29. if={level()<\SBLevel}{append={[,Stern Brocot*={#1}{#2}]}}{}},
  30. Stern Brocot/.style n args={5}{
  31. /utils/exec=\edef\SBLevel{#5},@Stern Brocot={#1}{#2}{#3}{#4}},
  32. @Stern Brocot/.style n args={4}{
  33. /utils/exec=\edef\SBTop{\number\numexpr#1+#3\relax}%
  34. \edef\SBBottom{\number\numexpr#2+#4\relax},
  35. content/.expanded=$\frac{\SBTop}{\SBBottom}$,
  36. if/.expanded={level()<\SBLevel}{% true
  37. append={[,@Stern Brocot={#1}{#2}{\SBTop}{\SBBottom}]},
  38. append={[,Stern Brocot*={\SBTop}{\SBBottom}]},
  39. append={[,@Stern Brocot={\SBTop}{\SBBottom}{#3}{#4}]}
  40. }{}}% false (empty)
  41. [,Stern Brocot={0}{1}{1}{0}{4}]
  42. %
  43. \coordinate[Stern Brocot at=1] (SB@left) coordinate[Stern Brocot at=3] (SB@right);
  44. \foreach \SBLLoop in {\SBLevel, ..., 0}
  45. \path node[Stern Brocot at*={1}{\SBLLoop}{left}] (SB@left@\SBLLoop) {$\frac01$}
  46. node[Stern Brocot at*={3}{\SBLLoop}{right}] (SB@right@\SBLLoop) {$\frac10$};
  47. \end{forest}
  48. \end{document}