Skip to content

Instantly share code, notes, and snippets.

@CasperCL
Last active May 10, 2018 15:56
Show Gist options
  • Save CasperCL/374644eb262f991ed760bbc0f4ae3b38 to your computer and use it in GitHub Desktop.
Save CasperCL/374644eb262f991ed760bbc0f4ae3b38 to your computer and use it in GitHub Desktop.
Mandelbrot in Go πŸƒβ€β™‚οΈ
package main
import (
"os"
"math"
"image"
"flag"
"image/png"
"image/color"
)
func scale(value float64, minA float64, maxA float64, minB float64, maxB float64) float64 {
// Scales a float from number range A to range B.
return ((value / (math.Abs(minA) + math.Abs(maxA))) * (math.Abs(minB) + math.Abs(maxB))) + minB
}
func mandelbrotColors() [16]color.RGBA {
// RGBA colors from https://stackoverflow.com/a/16505538
return [...]color.RGBA {
color.RGBA{66, 30, 15, 255},
color.RGBA{25, 7, 26, 255},
color.RGBA{9, 1, 47, 255},
color.RGBA{4, 4, 73, 255},
color.RGBA{0, 7, 100, 255},
color.RGBA{12, 44, 138, 255},
color.RGBA{24, 82, 177, 255},
color.RGBA{57, 125, 209, 255},
color.RGBA{134, 181, 229, 255},
color.RGBA{211, 236, 248, 255},
color.RGBA{241, 244, 191, 255},
color.RGBA{248, 201, 95, 255},
color.RGBA{255, 170, 0, 255},
color.RGBA{204, 128, 0, 255},
color.RGBA{153, 87, 0, 255},
color.RGBA{106, 52, 3, 255},
}
}
func CreateMandelbrotImage(width int, height int, maxIteration int, colors [16]color.RGBA) *image.RGBA {
// Creates an in memory image and fills it pixel by pixel with mandelbrotColors
mandelbrotImage := image.NewRGBA(image.Rect(0, 0, width, height))
// Implementation of https://en.wikipedia.org/wiki/Mandelbrot_set#Escape_time_algorithm
for Px := 0; Px < width; Px++ {
for Py := 0; Py < height; Py++ {
var x0 float64 = scale(float64(Px), 0, float64(width), -2.5, 1);
var y0 float64 = scale(float64(Py), 0, float64(height), -1, 1);
var x, y float64 = 0, 0;
iteration := 0;
for ; x*x + y*y < 2*2 && iteration < maxIteration; iteration++ {
xTemp := x*x - y*y + x0;
y = 2*x*y + y0;
x = xTemp;
}
color := colors[(iteration % len(colors))]
mandelbrotImage.Set(Px, Py, color)
}
}
return mandelbrotImage
}
func main() {
var width, height, iteration int
flag.IntVar(&width, "w", 1000, "specify width to use. defaults to 1024.")
flag.IntVar(&height, "h", 600, "specify height to use. defaults to 1024.")
flag.IntVar(&iteration, "i", 10, "specify iterations to use. defaults to 40.")
flag.Parse()
img := CreateMandelbrotImage(width, height, iteration, mandelbrotColors())
file, err := os.Create("mandelbrot.png")
if err != nil {
panic(err)
}
defer file.Close()
png.Encode(file, img)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment