Welcome, guest | Sign In | My Account | Store | Cart

C Fractal using recursion.

Python, 29 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# C fractal using recursion
# FB - 201007187
from PIL import Image, ImageDraw
import math

imgx = 512
imgy = 512
image = Image.new("L", (imgx, imgy))
draw = ImageDraw.Draw(image)

def c (xa, ya, xb, yb):
    global draw
    xd = xb - xa
    yd = yb - ya
    d = math.hypot(xd, yd)
    if d < 2: return
    x = xa + xd * 0.5 - yd * 0.5
    y = ya + xd * 0.5 + yd * 0.5
    draw.line ([(int(xa), int(ya)),(int(x), int(y))], 255)
    draw.line ([(int(x), int(y)),(int(xb), int(yb))], 255)
    c(xa, ya, x, y)
    c(x, y, xb, yb)

# main
mx = imgx -1
my = imgy - 1
c(mx / 4, my / 4, mx - mx / 4, my / 4)

image.save("c.png", "PNG")

1 comment

Thanasis Stamos 11 years, 4 months ago  # | flag

Nice.With a little effort it can be even nicer. Every time a recursion is done, we can change the color of the line, so that the wave length of light of this color increases. The code which transforms wave length to RGB color is given in http://www.johnny-lin.com/pylib.shtml. Here is the code:

# C fractal using recursion
# FB - 201007187
from PIL import Image, ImageDraw
import math
from wavelen2rgb import wavelen2rgb

imgx = 512
imgy = 512
image = Image.new("RGB", (imgx, imgy))
draw = ImageDraw.Draw(image)

def c (xa, ya, xb, yb, wav=380.0):
    global draw
    xd = xb - xa
    yd = yb - ya
    d = math.hypot(xd, yd)
    if d < 2: return
    x = xa + xd * 0.5 - yd * 0.5
    y = ya + xd * 0.5 + yd * 0.5
    wav = min((wav+20.0, 780.0))
    rgb = tuple(wavelen2rgb(wav, 255))
    draw.line ([(int(xa), int(ya)),(int(x), int(y))], rgb)
    draw.line ([(int(x), int(y)),(int(xb), int(yb))], rgb)
    c(xa, ya, x, y, wav)
    c(x, y, xb, yb, wav)

# main
mx = imgx -1
my = imgy - 1
c(mx / 4, my / 4, mx - mx / 4, my / 4)
image.save("c.png", "PNG")