Skip to content

Instantly share code, notes, and snippets.

@markusos
Created November 25, 2013 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markusos/7650217 to your computer and use it in GitHub Desktop.
Save markusos/7650217 to your computer and use it in GitHub Desktop.
mandelbrot.go - Draw the Mandelbrot set using GO
package main
import (
"image"
"image/color"
"image/png"
"log"
"math/cmplx"
"os"
)
type Canvas struct {
image.RGBA
}
func mandelbrot(canvas *Canvas) {
size := canvas.Bounds().Size()
center := complex(-0.5, 0)
zoom := 0.5
iter := 50
for x := 0; x < size.X; x++ {
for y := 0; y < size.Y; y++ {
n := 0
z := complex(0, 0)
xi := float64(x-size.X/2) / (zoom * float64(size.X/2))
yi := float64(y-size.Y/2) / (zoom * float64(size.Y/2))
c := center + complex(xi, yi)
for cmplx.Abs(z) < 2 && n < iter {
z = z*z + c
n = n + 1
}
co := float64(n) / float64(iter)
canvas.Set(x, y, color.RGBA{
0,
0,
uint8(255 * co), 255})
}
}
}
func saveImage(canvas *Canvas) {
outFilename := "mandelbrot.png"
outFile, err := os.Create(outFilename)
if err != nil {
log.Fatal(err)
}
defer outFile.Close()
png.Encode(outFile, canvas)
}
func main() {
width, height := 800, 800
canvas := new(Canvas)
canvas.RGBA = *image.NewRGBA(image.Rect(0, 0, width, height))
mandelbrot(canvas)
saveImage(canvas)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment