我正在尝试将概述的方程式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语句时犯了一个错误,因为这里展示的数学知识有些超出了我的教育范围。是这样吗?如果是这样,应该如何表达?
最佳答案
这里至少有一个错误。你有这个:
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
在你剧本的顶端。