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):


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,
   (*right[20 Degree];*)
   left[-20 Degree];
   tree[n - 15];
   left[40 Degree];
   tree[n - 15];
   (*right[20 Degree];*)
   left[-20 Degree];

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

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 °}}]
  • $\begingroup$ Your Mathematica code works to produce a simple tree. What exactly is the problem here? $\endgroup$
    – MarcoB
    Aug 21 '17 at 20:46
  • 2
    $\begingroup$ 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. $\endgroup$ Aug 22 '17 at 1:38
  • $\begingroup$ You created it? You should add reference mathematica.stackexchange.com/questions/63938/… $\endgroup$
    – partida
    Oct 7 '17 at 13:42

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]
  • $\begingroup$ 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. $\endgroup$
    – J. M.'s torpor
    Aug 22 '17 at 3:53
  • 1
    $\begingroup$ @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. $\endgroup$ Aug 22 '17 at 4:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.