无法将分形方程转换为Python算法

时间:2013-10-26 20:11:16

标签: python algorithm math procedural-generation

我正在尝试将here概述的等式转换为Python代码:

r = +/- (1+1.414sin(theta)cos(theta)-0.5cos(theta)cos(theta))^(1/6)exp(-0.4714(theta))

这是我的结果(因测试目的而略有黑客攻击):

import random
import pygame
import math
from pygame.locals import *

def random_spiral_pos(maxradius,theta=None):
    "Finds a random position in a spiral galaxy pattern."
    #Get a random angle (in rad). Could do this with a random 
    #variable in the range (0,2*pi), but this i clearer if inefficient
    if theta == None:
        theta=math.radians(random.randint(0,360))

    #Then use a fractal equation to get distance from center as a function
    #of angle
    #Source: http://www.philica.com/display_observation.php?observation_id=52
    r = (1+1.414*math.sin(theta)*math.cos(theta) -0.5*math.cos(theta)*math.cos(theta))**(1/6)*math.exp(-0.4714*theta)

    print(r)

    #R will be in the range 0-1, so we multiply it by
    #the radius of our drawing area
    r=r*maxradius

    #Convert the angle into polar coordinates, give the resultant vector
    #magnitude R (polar coordinates are a direction vector from the 
    #origin), then floor those values so Pygame can use them
    x=math.floor(math.cos(theta)*r)
    y=math.floor(math.sin(theta)*r)

    x=x+maxradius//2
    y=y+maxradius//2
    return (x,y)


if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((600,600))
    clock=pygame.time.Clock()
    pygame.key.set_repeat(25,5)

    #Main loop
    while 1:

        #timing
        clock.tick(60)

        #gfx
        screen.fill((0,0,0))
        screen.lock()
        for t in range (0,360):
            screen.set_at(random_spiral_pos(100,math.radians(t)),(255,255,255))
        screen.unlock()
        pygame.display.flip()

然而,结果似乎只是一个简单的螺旋。我很可能在将数学函数转换为Python语句时犯了一个错误,因为这里展示的数学是我教育之外的一些方法。是这种情况,如果是这样,应该如何表达?

1 个答案:

答案 0 :(得分:3)

这里至少有一个错误。你有这个:

r = (1+1.414*math.sin(theta)*math.cos(theta)*-0.5*math.cos(theta)*math.cos(theta))**(1/6)*math.exp(-0.4714*theta)

并且,根据链接,它应该是这样的:

r = (1+1.414*math.sin(theta)*math.cos(theta) -0.5*math.cos(theta)*math.cos(theta))**(1/6)*math.exp(-0.4714*theta)

另外,请注意 Python 中的(1/6)等表达式。如果你正在使用 Python2.X ,那么这将执行整数除法,结果为0。要将浮点除法作为标准,您需要输入

from __future__ import division

位于脚本的顶部。