Created
October 14, 2016 21:11
-
-
Save meysampg/83beb53c2714bbbee587b310bc175bee to your computer and use it in GitHub Desktop.
Extended Version of a Example in Kernighan Book
This file contains 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 ( | |
"flag" | |
"image" | |
"image/color" | |
"image/png" | |
"math/cmplx" | |
"os" | |
// "math" | |
"runtime" | |
"sync" | |
"time" | |
) | |
const ( | |
xmin, ymin, xmax, ymax = -2, -2, 2, 2 | |
) | |
func main() { | |
// Let Go to use all CPU cores | |
runtime.GOMAXPROCS(runtime.NumCPU()) | |
var mu sync.Mutex | |
// Parse command arguments | |
var width = flag.Int("w", 400, "Width of output image") | |
var height = flag.Int("h", 400, "Height of output image") | |
flag.Parse() | |
stepX := (xmax - xmin) / float64(*width) | |
stepY := (ymax - ymin) / float64(*height) | |
// Create Image Variable | |
img := image.NewRGBA(image.Rect(0, 0, *width, *height)) | |
for y := 0; y < *height; y++ { | |
go plotX(y, stepX, stepY, width, img, mu) | |
} | |
// Write to file | |
fileName := time.Now().Format(time.RFC3339) + ".png" | |
fp, err := os.Create(fileName) | |
defer fp.Close() | |
if err != nil { | |
panic(err) | |
} | |
png.Encode(fp, img) | |
} | |
func plotX(y int, stepX float64, stepY float64, width *int, img *image.RGBA, mu sync.Mutex) { | |
yInCPlane := stepY*float64(y) + ymin | |
for x := 0; x < *width; x++ { | |
xInCPlane := stepX*float64(x) + xmin | |
z := complex(xInCPlane, yInCPlane) | |
mu.Lock() | |
img.Set(x, y, mandelbrot(z)) | |
mu.Unlock() | |
} | |
} | |
func mandelbrot(z complex128) color.Color { | |
var v complex128 | |
for i := uint8(0); i <= 127; i++ { | |
v = v*v + z | |
if cmplx.Abs(v) > 2 { | |
return colorCreator(i) | |
} | |
} | |
return color.Black | |
} | |
func colorCreator(step uint8) color.RGBA { | |
return color.RGBA{255 - step*10, 127 - step*10, step * 10, 0xFF} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I must work on coloring and zooming features.
![2016-10-15t00 25 25 03 30](https://cloud.githubusercontent.com/assets/1416085/19410365/3e745c9c-92f7-11e6-9517-605d7ba03978.png)