python - 实现科赫曲线?

标签 python fractals

我在查看 Koch Snowflake (here) 的维基百科页面时,被所有采用 Logo /海龟样式的示例所困扰。所以我开始制作自己的返回列表或坐标的。

我的实现是在 python 中,我基本上撕掉了 python turtle 实现,但用基本的 trig 替换了 turtle 特定的东西。它导致了一些丑陋的代码。我对你的挑战是要么改进我的代码,要么想出一个你自己的更巧妙的解决方案。它可以使用 Python 或您喜欢的语言。

我的代码:

from math import sin, cos, radians

def grow(steps, length = 200, startPos = (0,0)):
    angle = 0
    try:
        jump = float(length) / (3 ** steps)
    except:
        jump = length

    set="F"
    for i in xrange(steps): set=set.replace("F", "FLFRFLF")

    coords = [startPos]
    for move in set:
        if move is "F": 
            coords.append(
              (coords[-1][0] + jump * cos(angle),
               coords[-1][1] + jump * sin(angle)))
        if move is "L":
            angle += radians(60)
        if move is "R":
            angle -= radians(120)

    return coords

编辑:由于懒惰复制,我忘记了导入

最佳答案

我不认为它特别难看,我只会逐步重构它,例如作为第一步(我已经删除了 try/except 因为我不知道你想阻止什么......如果它需要回到它应该多一点明确的,恕我直言):

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 grow(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

如果有必要采取第二步,我可能会把这个功能整合到一个类中,但我不确定这是否会让事情变得更好(或者,实际上更好;-)。

关于python - 实现科赫曲线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/932222/

相关文章:

python - 在 Python 中获取 ctypes 结构的二进制表示

python - 如何修复 "error: error in setup.cfg: command ' bdist_wheel' 没有这样的选项 'universal' "

python - 如何解释 sklearn.tree.tree_tree.value 属性的(意外)值?

javascript - 在计算 mandelbrot 集迭代时遇到问题

java - Mandelbrot刷新速度很慢,有什么办法可以让它更快吗?

python - 如何配置构建以使用 bin/sphinxbuilder 创建 sphinx 文档

python - #@save 定义和重要性 python

3d - 如何渲染Mandelbulb样式的3D分形

image - 在 MATLAB 绘图中创建分形图像,但绘图为空

c# - 中点位移算法 - 奇怪的结果