Julia Sets and Fractals

Today, I implemented Julia sets in Ruby and C. First, I prototyped a Ruby version, then quickly recognized that it is simply too slow to generate larger images. So I translated it to C which resulted in a performance boost of factor 180! Here's the fractal created by the example:

The Ruby version is given below. It creates PNM bitmap files, which can be viewed for example with display on Unix-like operating systems.

Feel free to modify the parameters, especially c, rx and ry. And of course the colormap.

require "complex"

c = Complex(-0.75, 0.136)          # the Julia set parameter
iters = 50                         # max iterations
w, h = 1400, 700                   # bitmap extents
rx, ry = -1.0 .. 1.0, -1.0 .. 1.0  # view area

sx = (rx.last - rx.first).abs / w  # x-scale
sy = (ry.last - ry.first).abs / h  # y-scale

colmap = Array.new(256, "\000"*3)  # color map

# initialize colormap
(1..255).each {|i| colmap[i] = [10+i*10, 0, rand*100].pack("CCC") } 

# write PNM header
print "P6\n#{w} #{h}\n255\n"

# do the real stuff
for j in 0...h
  for i in 0...w
    n, zn = 0, Complex(sx*i+rx.first, sy*j+ry.first)
    while n <= iters 
      # sequence runs away to infinity
      break if (zn-c).abs > 2

      # calculate next iteration
      zn = zn**2 + c; n += 1
    end

    # draw/print pixel 
    print colmap[n] 
  end
end

The same example written more compactly with only 229 bytes :-)

require"complex";c,m,w,h=Complex(-0.75,0.136),50,1400,700
puts "P6\n#{w} #{h}\n255";(0...h).each{|j|(0...w).each{|i|
n,z=0,Complex(0.9*i/w,0.9*j/h)
while n<=m&&(z-c).abs<=2;z=z*z+c;n+=1 end
print [20+n*10,0,rand*99].pack("C*")}}

Or on the command line:

ruby -rcomplex -e'c,m,w,h=Complex(-0.75,0.136),50,1400,700;\
puts"P6\n#{w} #{h}\n255";(0...h).each{|j|(0...w).each{|i|n,\
z=0,Complex(0.9*i/w,0.9*j/h);while n<=m&&(z-c).abs<=2;z=z*z+c;\
n+=1 end;print [20+n*10,0,rand*99].pack("C*")}}'|display