Skip to content

Instantly share code, notes, and snippets.

@mixmix
Last active August 29, 2015 14:01
Show Gist options
  • Save mixmix/6a7eb72991458d63e15a to your computer and use it in GitHub Desktop.
Save mixmix/6a7eb72991458d63e15a to your computer and use it in GitHub Desktop.
run it in terminal... you'll need to zoom out a fair bit
require 'curses'
class ComplexNum
attr_reader :re, :im
def initialize(re: 0, im:0)
@re = re
@im = im
end
def +(b)
real = @re + b.re
imag = @im + b.im
ComplexNum.new(re: real, im: imag)
end
def *(b)
real = @re * b.re - @im * b.im
imag = @re * b.im + @im * b.re
ComplexNum.new(re: real, im: imag)
end
def sq
real = @re**2 - @im**2
imag = 2* @re * @im
ComplexNum.new(re: real, im: imag)
end
def mod
Math.sqrt(@re**2 + @im**2)
end
def in?
return false if (@re >= 2 || @im >= 2)
self.mod <= 2
end
def n_times(n, function)
i = self
n.times { i = function.call(i) }
i
end
end
class Screen
attr_accessor :coords_0, :coords_n, :n, :history
def initialize(view_radius=2.0, pixels=41)
spacing = 2*view_radius / (pixels-1).to_f
coords = []
(0...pixels).each do |j|
row = []
(0...pixels).each do |i|
real = -view_radius + i*spacing
imag = view_radius - j*spacing
row << ComplexNum.new(re: real, im: imag)
end
coords << row
end
@coords_0 = coords # c
@coords_n = coords # z_n
@n = 1
@history = [ ]
end
def map(&block)
mapd_array = []
coords_n.count.times { mapd_array << []}
coords_n.each_with_index do |row, j|
row.each_with_index do |coord, i|
mapd_array[j][i] = block.call(j,i)
end
end
mapd_array
end
def evaluate
map {|j,i| coords_n[j][i].in? }
end
def transform
@coords_n = map { |j,i| @coords_n[j][i].sq + @coords_0[j][i] }
history << self.evaluate
n = @n+1
end
def to_s(i = (history.count-1) )
in_char = " *" #" \e[32m*\e[0m"
out_char = " "
output = ""
@history[i].each do |row|
row.each do |coord|
output += coord ? in_char : out_char
end
output += "\n"
end
output
end
def play(framerate=0.5)
#Curses.init_screen
(0...history.count).each do |snap|
Curses.clear
Curses.setpos(0,0)
Curses.addstr(to_s(snap))
Curses.refresh
sleep(framerate)
end
#Curses.close_screen
end
end
s = Screen.new(2, 201)
s.history << s.evaluate
20.times {
s.transform
print '.'
}
print "\n"
s.play(0.2)
10.times { s.play(0.1) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment