Help for fractals.

30 views
Skip to first unread message

BRCamy

unread,
Apr 16, 2018, 4:51:33 PM4/16/18
to VPython-users
I'm new to python and vPython, and I was wondering if someone could help me make a Sierpinski triangle, I'm not sure how to do it but any help will be greatly appreciated. Thanks.

Kadir Haldenbilen

unread,
Apr 18, 2018, 2:08:49 AM4/18/18
to VPython-users
Drawing fractals is more of an algorithm issue; that is, you need to have a recursive algorithm to get the triangles at some "depth" level. You can find algorithms on the net by searching with parameters lke Sierpinski triangle algorithm.

There is one such example and algorith at the link below with python turtle:

http://interactivepython.org/runestone/static/pythonds/Recursion/pythondsSierpinskiTriangle.html

You can adapt that code to vpython like:



from vpython import *

def drawTriangle(points,color):
    curve(pos=[points[0].pos,points[1].pos], color=color)
    curve(pos=[points[1].pos,points[2].pos], color=color)
    curve(pos=[points[2].pos,points[0].pos], color=color)
    triangle(vs=[points[0], points[1], points[2]])

def getMid(p1, p2, color):
    return vertex(pos=(p1.pos+p2.pos) /2.0, color=color)

colormap = [color.blue, color.red, color.green, color.white, color.yellow, color.magenta, color.orange]
def sierpinski(points,degree):
    drawTriangle(points,colormap[degree])
    if degree > 0:
        sierpinski([points[0], getMid(points[0], points[1], colormap[degree]), getMid(points[0], points[2], colormap[degree])], degree-1)
        sierpinski([points[1], getMid(points[0], points[1], colormap[degree]), getMid(points[1], points[2], colormap[degree])], degree-1)
        sierpinski([points[2], getMid(points[2], points[1], colormap[degree]), getMid(points[0], points[2], colormap[degree])], degree-1)

myPoints = [vertex(pos=vec(-100,-50,0), color=colormap[0]),vertex(pos=vec(0,100,0), color=colormap[0]),vertex(pos=vec(100,-50,0), color=colormap[0])]
sierpinski(myPoints,3)

should give you a similar triangle fractal at depth level 3. Changing depth level, you can get more number of sub triangles.


16 Nisan 2018 Pazartesi 23:51:33 UTC+3 tarihinde BRCamy yazdı:
Reply all
Reply to author
Forward
0 new messages