Skip to content

Instantly share code, notes, and snippets.

@siddMahen
Last active August 29, 2015 14:22
Show Gist options
  • Save siddMahen/cc5d6750a3ac3240c375 to your computer and use it in GitHub Desktop.
Save siddMahen/cc5d6750a3ac3240c375 to your computer and use it in GitHub Desktop.
Drawing the Koch fractal using Julia and Compose.
using Compose
function koch_side(n)
if n == 1
return compose(context(),
line([(0,1),(1/3,1),(1/2, 1 - (sin(pi/3)/3)),(2/3,1),(1,1)]))
else
ks = koch_side(n - 1)
return compose(context(),
(context(0,2/3,1/3,1/3), ks),
(context(1/3,2/3,1/3,1/3, rotation=Rotation(-pi/3,(0,1))), ks),
(context(1/3,2/3,1/3,1/3, rotation=Rotation(pi/3, (1,1))), ks),
(context(2/3,2/3,1/3,1/3), ks))
end
end
function koch(n)
if n == 0
return compose(context(), polygon([(1/2, 1-sin(pi/3)), (0,1), (1,1)]))
else
side = koch_side(n)
fside = compose(context(rotation=Rotation(pi)),side)
c = (sin(pi/3)/3) + 1/3
return compose(context(),
(context(1/3,0,1/3,1/3), side),
(context(1/6,c,1/3,1/3, rotation=Rotation(pi/3,(1,0))), fside),
(context(1/2,c,1/3,1/3, rotation=Rotation(-pi/3,(0,0))), fside))
end
end
draw(SVG("koch.svg", 5inch, 5inch),
compose(koch(7), stroke("black"), fill(nothing), linewidth(0.1mm)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment