科赫曲线
科赫曲线是一种不规则碎片,具有递归结构的图形,可以通过下述递归函数的调用画出:

  • 将给定线段(p1,p2)(p_1,p_2)三等分
  • 以三等分点s,ts,t为顶点作出正三角形(s,u,t)(s,u,t)
  • 对线段(p1,s)(p_1,s),线段(s,u)(s,u),线段(u,t)(u,t),线段(t,p2)(t,p_2)递归地重复进行上述操作

设端点为(0,0),(100,0)(0,0),(100,0)
输入: 1个整数nn
输出:科赫曲线各顶点的坐标(x,y)(x,y),每个点的坐标占1行。
限制:0n70\leq n\leq7

问题解决:
n=1n=1时,求u的坐标时,要用到二维的旋转矩阵
[cos(θ)sin(θ)sin(θ)cos(θ)]\begin{bmatrix} cos(\theta) & -sin(\theta)\\ sin(\theta)& cos(\theta) \end{bmatrix}
st\vec{st}逆时针旋转60度得到su\vec{su},所以:
[uxsxuysy]=[cos(θ)sin(θ)sin(θ)cos(θ)][txsxtysy]\begin{bmatrix} u_x-s_x\\u_y-s_y \end{bmatrix} =\begin{bmatrix} cos(\theta) & -sin(\theta)\\ sin(\theta)& cos(\theta) \end{bmatrix} \begin{bmatrix} t_x-s_x\\t_y-s_y \end{bmatrix}
由此可以得到u的坐标。

##  koch  ##
# author:Halie
import math
class point:
    def _init_(self):
        self.x=0
        self.y=0

def koch(n,p1,p2):
    if n==0:
        return
    s,t,u=point(),point(),point()
    theta=math.pi / 3
    s.x=p1.x+(p2.x-p1.x)/3.
    s.y=p1.y+(p2.y-p1.y)/3.
    t.x=p2.x-(p2.x-p1.x)/3.
    t.y = p2.y - (p2.y - p1.y) / 3.
    u.x=math.cos(theta)*(t.x-s.x)-math.sin(theta)*(t.y-s.y) +s.x
    u.y = math.sin(theta) * (t.x - s.x) + math.cos(theta) * (t.y - s.y) +s.y
    koch(n-1,p1,s)
    print("(%.8f,%.8f)"%(s.x,s.y))
    koch(n-1,s,u)
    print("(%.8f,%.8f)" % (u.x, u.y))
    koch(n-1,u,t)
    print("(%.8f,%.8f)" % (t.x, t.y))
    koch(n-1,t,p2)

p1,p2=point(),point()
p1.x=0
p1.y=0
p2.x=100
p2.y=0
n = int(input("请输入一个整数:"))
print("(%.8f,%.8f)" % (p1.x, p1.y))
koch(n,p1,p2)
print("(%.8f,%.8f)" % (p2.x, p2.y))

补充:
科赫曲线
科赫曲线

相关文章: