Skip to content

Instantly share code, notes, and snippets.

@domgetter
Created December 10, 2015 13:16
Show Gist options
  • Save domgetter/800995c0f27a476cf67f to your computer and use it in GitHub Desktop.
Save domgetter/800995c0f27a476cf67f to your computer and use it in GitHub Desktop.
;; Winner winner, chicken dinner. This calcs (mandel (complex. 0 0) 2000) in 15 μs after warmup
(deftype complex [^double real ^double imag])
(defn plus
"(a + bi) + (c + di) == (a + b) + (c + d)i"
[^complex z1 ^complex z2]
(complex. (+ (.real z1) (.real z2)) (+ (.imag z1) (.imag z2))))
(defn magnitude-squared
"|z|^2 == a^2 + b^2"
[^complex z]
(+ (* (.real z) (.real z)) (* (.imag z) (.imag z))))
(defn times
"(a + bi)*(c + di) == (ac - bd) + (ad + bc)i"
[^complex z1 ^complex z2]
(complex.
(- (* (.real z1) (.real z2)) (* (.imag z1) (.imag z2)))
(+ (* (.real z1) (.imag z2)) (* (.imag z1) (.real z2)))))
(defn mandel
"Calculates the number of iterations taken to escape, up to a bailout
(mandel (complex. 0 0) 100) => 100 since [0,0] is in the set"
([^complex c ^long dwell]
(mandel (complex. 0 0) c 0 dwell))
([z c ^long its ^long dwell]
(if (or (> (magnitude-squared z) 4.0) (= its dwell))
its
(recur (plus (times z z) c) c (inc its) dwell))))
;; for example
(for [x (range -2 2 0.01)
y (range -2 2 0.01)]
(mandel (complex. x y) 200))
;; will produce the bailout values for all [x, y] coordinates [-2,-2], [-2,-1.99], [-2,-1.98], ... [2,1.99], [2,2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment