Skip to content

Instantly share code, notes, and snippets.

@edma2
Created June 25, 2012 08:21
Show Gist options
  • Save edma2/2987347 to your computer and use it in GitHub Desktop.
Save edma2/2987347 to your computer and use it in GitHub Desktop.
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
import java.io.File
/** The Mandelbrot image with given width and height in pixels. */
class Mandelbrot(width: Int, height: Int) {
case class Complex(re: Double, im: Double) {
def *(op: Complex): Complex = {
Complex(re * op.re - im * op.im, re * op.im + im * op.re)
}
def +(op: Complex): Complex = Complex(re + op.re, im + op.im)
def bounded = re < 2 && im < 2
}
/** Scaled from x and y coordinates. */
def fromPoint(x: Int, y: Int): Complex = {
Complex(3.5*(x.toDouble / width)-2.5, 2*(y.toDouble / height)-1)
}
def draw(path: String) {
val image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
for (x <- 0 until width) {
for (y <- 0 until height) {
val c = fromPoint(x, y)
println(c.re + " " + c.im)
val rgb = escapeTime(c, 100)
image.setRGB(x, y, rgb)
}
}
ImageIO.write(image, "png", new File(path))
}
/* z(0) = 0
* z(n+1) = z(n)^2 + c */
def z(c: Complex): Stream[Complex] = {
Complex(0, 0) #:: z(c) map {zn => zn * zn + c}
}
/** The number of iterations required to escape.
* Returns max if c does not escape. */
def escapeTime(c: Complex, max: Int): Int = {
z(c) zip (0 to max) takeWhile {e => e._1.bounded && e._2 < max} size
}
}
object Test {
def main(args: Array[String]) {
val m = new Mandelbrot(5000, 3000)
m.draw("test.png")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment