Topic

L-systems

An L-system rewrites every symbol of a string at once, then a turtle draws the result. The strings grow exponentially, but how many of each symbol they hold is a matrix power, exact for any n, and for angles that are multiples of 30° every point the turtle visits is exactly a + b√3.

const K = lsystems.koch();                  // axiom F, F → F+F--F+F, angle 60°
K.generate(2);                               // the string after two rewritings
K.counts(100).counts.F;                      // 4^100, exactly, without writing the string
K.turtle(3).exactSegments;                   // end points as Q3 numbers a + b√3
lsystem({ axiom: "X", rules: { X: "F+[[X]-X]-F[-FX]+X", F: "FF" }, angle: 25 });

Parallel rewriting

An L-system has an axiom and rules mapping single symbols to strings; symbols without a rule are copied. One step rewrites every symbol at the same time. Lindenmayer used them for the growth of plants, where every cell divides at once. generate(n) writes the string out, refusing past five million symbols.

Counting without writing

Let MabM_{ab} be the number of b in the rule for a. If vv counts the symbols of the axiom, then vMnv M^n counts the symbols after n steps, and repeated squaring gives MnM^n with BigInt entries in about log⁡2n\log_2 n multiplications. For the Koch curve M has the eigenvalue 4, so the curve has 4n4^n segments, each 3−n3^{-n} long: its length (4/3)n(4/3)^n grows without bound while it stays in a bounded region. For the dragon the counts follow powers of 2.

The turtle, exactly

F and G draw a unit step, f moves without drawing, + and − turn by the angle, | turns around, and [ ] save and restore the position and heading. When the angle is a multiple of 30°, cos⁡\cos and sin⁡\sin of every heading are among 0,±12,±1,±320, \pm\tfrac12, \pm1, \pm\tfrac{\sqrt3}2, so every position is a+b3a + b\sqrt3 with rational a and b. The library carries those as Q3 numbers, which is how it can say the Koch snowflake closes up exactly: its end point is (0, 0), not something within 10⁻¹⁵ of it. Other angles (the 25° plant, the 45° Lévy curve) are drawn in floats and the result says kind: "float".

callreturns
lsystem({ axiom, rules, angle, draw = "FG", move = "f" })An LSystem
generate(n)The string
counts(n){ counts: { symbol: BigInt }, length: BigInt }
turtle(n, { step }){ kind, segments, exactSegments, end }
lsystemskoch, snowflake, arrowhead, dragon, hilbert, levy, plant
Q3a + b√3: add, mul, equals, toNumber, toString
Try itEdit the code and run it with @ratmath/chaos and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs