Python Forum

Full Version: How to write a recursion syntax for Sierpinski triangle using numpy?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I'm new to programming in python [total beginner in programming] and I would like to ask you for your help.

So here is my problem:
I'm trying to program a Sierpinski triangle for n-iterations. Here is what I got so far:

import numpy as np
from math import sqrt

#               a       b           c
P = np.array([(0, 0), (1, 0), (1, (1/sqrt(2)))], dtype=float)

# I could start with any point, but decided to start with a
a = np.array((0, 0), dtype=float)

new_point: #1.iteration
#    a   +  b
p1 = P[0] + P[1] new_point #2.iteration
                 t1 = P[0] + p1 
                 t2 = P[1] + p1  
                 t3 = P[2] + p1   
#    b   +  c 
p2 = P[1] + P[2] new_point #2.iteration
                 t4 = P[0] + p2 
                 t5 = P[1] + p2 
                 t6 = P[2] + p2 
#    c   +  a
p3 = P[2] + P[0] new_point #2.iteration
                 t7 = P[0] + p3 
                 t8 = P[1] + p3 
                 t9 = P[2] + p3 
My problem is writing all this in recursion syntax in python (recursion is mandatory).

[Image: YGm0dm.png]
[Image: R47xKm.png]

I even drew everything on the piece of paper, so I understand the algorithm, but don't know how to write it in syntax.

What about plotting all the points? Is there a 'grid' for these arrays? I read about numpy.zeros(), but it was explained this is a function for matrixes, so I'm not sure how to implement this into the program.

Can you help?
Why are you using numpy? Seems like it adds nothing to solving this problem.

Can you write code that solves the problem for 1 iteration? I don't think you have the logic correct for that. Once you have the code that computes the three similar triangles the recursion part is simple.
I would write a function which takes in 3 points for the triangle, makes 3 points for the triangle within it to get 3 sets of 3 points like so: [A, p1, p3], [B, p1, p2], [C, p2, p3]. Then it executes itself with each set of three points. You can figure out what to do with the points and how to tell the program to stop.

Example code: (Code is sorta untested by the way)
import numpy as np
from math import sqrt


def recursive(points):
    p1 = (points[0] + points[1]) / 2
    p2 = (points[1] + points[2]) / 2
    p3 = (points[2] + points[0]) / 2
    for p_set in np.array([points[0], p1, p3], [points[1], p1, p2], [points[2], p3, p2]):
        recursive(p_set)


recursive(np.array([[0, 0], [1, 0], [1, 1/sqrt(2)]]))