2

Here is a Python turtle code for making a fractral tree, I had translation it to mathematica code(see Make a series of points curl):

Clear["`*"];

initial[position_, th_] :=
  Module[{θ = th, pos = position},
   left := θ += # &;
   right := θ -= # &;
   forward := (pos += #*{Cos[θ], Sin[θ]}; Sow[pos];) &;
   backward := (pos -= #*{Cos[θ], Sin[θ]}; Sow[pos];) &;
   ];

tree[n_] :=
  If[n > 5,
   forward[n];
   (*right[20 Degree];*)
   left[-20 Degree];
   tree[n - 15];
   left[40 Degree];
   tree[n - 15];
   (*right[20 Degree];*)
   left[-20 Degree];
   backward[n]
   ];

initial[{0, 0}, Pi/2];(*initial conditions*)
point = Reap[tree[15 5]][[2, 1]];
Graphics[Line[point]]

I found AnglePath would be better for this, but I don't know how to programmingly do this.

Graphics@Line@AnglePath[{{0,0},-(π/2)},{{45,180 °},{30,-20 °},  
{15,-20 °},{15,180 °},{15,-140 °},{15,180 °},{30,-20 °},
{30,-140 °},{15,-20 °},{15,180 °},{15,-140 °},{15,180 °},{30,-20 °},{45,-20 °}}]
matrix42
  • 6,996
  • 2
  • 26
  • 62
  • Your Mathematica code works to produce a simple tree. What exactly is the problem here? – MarcoB Aug 21 '17 at 20:46
  • 2
    I'm pretty sure he wants to get the function which does this for arbitrary n. I'm not sure AnglePath is the best function for this, since this involves a bunch of retracing. But it's probably better than that somewhat scary and non-local code. – Itai Seggev Aug 22 '17 at 01:38
  • You created it? You should add reference https://mathematica.stackexchange.com/questions/63938/make-a-series-of-points-curl/73527#73527 – partida Oct 07 '17 at 13:42

1 Answers1

5

Basically, you just want to translate those commands into what AnglePath wants, taking it account the current orientation. Forward is just going forward a distance $n$ with no rotation. Left is just rotating some many degrees over no distance. Because we don't want a extra level of list at each stage, we use Apply to retrun Sequence object at each stage. Also note that since the total rotation of each tree is 180 degrees, we must add 180 degrees in the middle to keep the orientation.

tree[n_] := If[n > 5,
  Sequence @@ {{n, 0}, {0, -20 Degree}, 
    tree[n - 15], {0, 220 Degree},
    tree[n - 15], {n, -20 Degree}}, Sequence @@ {}]

makeTree[θ0_, n_] := 
 Graphics@Line@AnglePath[{{0, θ0}, tree[n]}]

makeTree[Pi/2, 75]
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
Itai Seggev
  • 14,113
  • 60
  • 84
  • What tripped me up in trying to translate the Python code is that the turtle backtracks (just like in Logo!) and AnglePath[] does not without generating an overlapping segment. – J. M.'s missing motivation Aug 22 '17 at 03:53
  • 1
    @J.M. Yes, if you saw my comment on the question, I don't think either AnglePath or the original code are particularly good. I'm certainly not avoiding doubled edges. I just offer this as a more or less direct translation. – Itai Seggev Aug 22 '17 at 04:19