Created
November 18, 2018 17:21
-
-
Save meisterluk/703d2faf62fb45d1527db14e5156abd6 to your computer and use it in GitHub Desktop.
Mandelbrot in Golang (as PNG) based on @benhoyt's mandel.awk
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"image/color" | |
"image/png" | |
"image" | |
"fmt" | |
"os" | |
) | |
// based on https://github.com/benhoyt/goawk/blob/master/examples/mandel.awk | |
func main() { | |
width := 150 | |
height := 50 | |
minX := -2.1 | |
maxX := 0.6 | |
minY := -1.2 | |
maxY := 1.2 | |
iters := 32.0 | |
img := image.NewNRGBA(image.Rect(0, 0, width, height)) | |
colors := []color.NRGBA{ | |
color.NRGBA{0xFF, 0xFF, 0xFF, 0xFF}, | |
color.NRGBA{0xFF, 0xEE, 0xDD, 0xFF}, | |
color.NRGBA{0xEE, 0xCC, 0xAA, 0xFF}, | |
color.NRGBA{0xDD, 0xBB, 0x88, 0xFF}, | |
color.NRGBA{0xCC, 0xAA, 0x77, 0xFF}, | |
color.NRGBA{0xBB, 0x88, 0x66, 0xFF}, | |
color.NRGBA{0x99, 0x66, 0x33, 0xFF}, | |
color.NRGBA{0x66, 0x44, 0x22, 0xFF}, | |
color.NRGBA{0x00, 0x00, 0x00, 0xFF}, | |
} | |
incY := (maxY - minY) / float64(height) | |
incX := (maxX - minX) / float64(width) | |
y := minY | |
for row := 0; row < height; row++ { | |
x := minX | |
for col := 0; col < width; col++ { | |
zi := 0.0 | |
zr := zi | |
i := 0.0 | |
for ; i < iters; i++ { | |
oldZr := zr | |
zr = zr * zr - zi * zi + x | |
zi = 2 * oldZr * zi + y | |
if zr * zr + zi * zi > 4 { | |
break | |
} | |
} | |
img.Set(col, row, colors[int((i*8) / iters)]) | |
x += incX | |
} | |
y += incY | |
} | |
fd, err := os.Create("mandelbrot.png") | |
if err != nil { | |
panic(err) | |
} | |
if err := png.Encode(fd, img); err != nil { | |
fd.Close() | |
panic(err) | |
} | |
if err := fd.Close(); err != nil { | |
panic(err) | |
} | |
fmt.Println("File mandelbrot.png written") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment