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 be the number of b in the rule for a. If counts the symbols of the axiom, then counts the symbols after n steps, and repeated squaring gives with BigInt entries in about multiplications. For the Koch curve M has the eigenvalue 4, so the curve has segments, each long: its length 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°, and of every heading are among , so every position is 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".
| call | returns |
|---|---|
| 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 } |
| lsystems | koch, snowflake, arrowhead, dragon, hilbert, levy, plant |
| Q3 | a + b√3: add, mul, equals, toNumber, toString |
@ratmath/chaos and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.