<p>也许您应该尝试重新实现更规范的迭代计算。</p>
<p>下面是对Python中使用良好的Koch曲线算法的请求的答复:</p>
<p><a href="https://stackoverflow.com/questions/932222/implementing-the-koch-curve/932498#932498">Implementing the Koch Curve?</a></p>
<p>(而且问题中的原始代码可以帮助您很多)</p>
<p>编辑:
我创建了一个脚本,它使用来自提供的链接的代码,加上Cairo和Python图像库(PIL)来呈现图像。希望有帮助:</p>
<pre><code>#!/bin/env python
# coding: utf-8
import math
angles = [math.radians(60*x) for x in range(6)]
sines = [math.sin(x) for x in angles]
cosin = [math.cos(x) for x in angles]
def L(angle, coords, jump):
return (angle + 1) % 6
def R(angle, coords, jump):
return (angle + 4) % 6
def F(angle, coords, jump):
coords.append(
(coords[-1][0] + jump * cosin[angle],
coords[-1][1] + jump * sines[angle]))
return angle
decode = dict(L=L, R=R, F=F)
def koch(steps, length=200, startPos=(0,0)):
pathcodes="F"
for i in xrange(steps):
pathcodes = pathcodes.replace("F", "FLFRFLF")
jump = float(length) / (3 ** steps)
coords = [startPos]
angle = 0
for move in pathcodes:
angle = decode[move](angle, coords, jump)
return coords
TOTALWIDTH = 1000
points = koch(3,TOTALWIDTH,(-TOTALWIDTH/2,0))
print points
# optional part, shows an image with Y axis(good for debugging)
import cairo, Image
width = TOTALWIDTH
height = int(TOTALWIDTH*0.32)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
cr = cairo.Context(surface)
cr.set_source_rgb(1,1,1)
cr.rectangle(0, 0, width, height)
cr.fill()
cr.translate(width*0.5, height*0.95)
cr.scale(1, -1)
# red Y axis:
cr.set_source_rgb(1,0,0)
cr.move_to(0,0)
cr.line_to(0,300)
cr.stroke()
cr.set_source_rgb(0,0,0)
cr.set_line_width(0.5)
cr.move_to(*points[0])
for n in range(len(points)):
cr.line_to(*points[n])
cr.stroke()
im = Image.frombuffer("RGBA", (width, height), surface.get_data(), "raw", "BGRA", 0,1)
im.show()
</code></pre>