Search code examples
pythoncfractals

Cantor ternary set in Python or C


I would like to generate in Python or C the Cantor ternary set with help of a recursive function and I don't how to do it. More precisely I want that after N recursions Python returns something like a list which contains the beginning and the end of the subset which compose the Cantor set.


Solution

  • Here's what I came up with so you can compare your version:

    def cantor(n):
        return [0.] + cant(0., 1., n) + [1.]
    
    def cant(x, y, n):
        if n == 0:
            return []
    
        new_pts = [2.*x/3. + y/3., x/3. + 2.*y/3.]
        return cant(x, new_pts[0], n-1) + new_pts + cant(new_pts[1], y, n-1)
    
    for i in range(4):
        print(i, cantor(i))
    

    At each level of recursion, you just compute the two inner points, and patch those together with what the nested calls return.

    Here's the run with recursion limits 0..3:

    0 [0.0, 1.0]
    1 [0.0, 0.3333333333333333, 0.6666666666666666, 1.0]
    2 [0.0, 0.1111111111111111, 0.2222222222222222, 0.3333333333333333, 0.6666666666666666,0.7777777777777777, 0.8888888888888888, 1.0]
    3 [0.0, 0.037037037037037035, 0.07407407407407407, 0.1111111111111111, 0.2222222222222222, 0.25925925925925924, 0.2962962962962963, 0.3333333333333333, 0.6666666666666666, 0.7037037037037037, 0.7407407407407407, 0.7777777777777777, 0.8888888888888888, 0.9259259259259258, 0.9629629629629629, 1.0]