Sierpinski 曲线

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']

plt.rcParams['axes.unicode_minus'] = False

def replacement(str, rules, order):

    for i in range(order):

        dst = ""

        for s in str:

            if s in rules:

                dst += rules[s]

            else:

                dst += s

        str = dst

    return str

def interpretation(str, actions, rotate, angle, x, y):

    import math

    point_x = [x,]

    point_y = [y,]

    for s in str:

        if s not in actions:

            continue

        if actions[s] == "left":

            angle -= rotate

        elif actions[s] == "right":

            angle += rotate

        elif actions[s] == "forward":

            r = angle / 180.0 * math.pi

            point_x.append(point_x[-1] + math.cos(r))

            point_y.append(point_y[-1] + math.sin(r))

    return point_x, point_y

# Sierpinski arrowhead 曲线

grammer = {

  "start": "A",

  "rules": {"A": "B-A-B", "B": "A+B+A"},

}

geometry = {

  "rotate": 60,

  "actions": {"+": "left", "-": "right", "A": "forward", "B": "forward"}

}

##########################################################

fig, ax = plt.subplots(1, 5) 

for i in range(5):

    str = replacement(grammer["start"], grammer["rules"], i + 1)

    x, y = interpretation(str, geometry["actions"], geometry["rotate"], 30, 0, 0)

    sub = ax[i]

    sub.axis("off")

    sub.set_aspect("equal")

    sub.plot(x, y)

pl.title('系列Sierpinski 曲线',x=-2)

plt.show()


你可能感兴趣的:(Sierpinski 曲线)