4

我正在尝试将此处概述的方程式转换为 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 语句时出错了,因为这里展示的数学超出了我的教育范围。是这样吗,如果是,应该如何表达?

4

1 回答 1

4

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

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

在脚本的顶部。

于 2013-10-26T22:01:12.160 回答