Question

I'm trying to convert the equation outlined here into Python code:

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

This is my result (slightly hacked for testing purposes):

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

However, the result seems to merely be a simple spiral. It's likely that I've just made an error in converting the mathematical function to a Python statement, as the mathematics on display here are some ways beyond my education. Is this the case, and how should it be expressed if so?

Était-ce utile?

La solution

There's at least one mistake here. You have this:

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)

and, according to the link, it should be this:

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)

Also, be careful with expressions like (1/6) in Python. If you're using Python2.X, then this will perform integer division and the result is 0. To get floating point division as standard, you need to put

from __future__ import division

at the top of your script.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top