 |
Mandlebrot |
Mandlebrot set program in Go based on original ps5.js program by Codingtrain
package main
import (
"fmt"
"image"
"image/png"
"image/color"
"os"
)
func main() {
// set image width and height in pixels
image_width := 1000
image_height := 1000
// Create a blank image
myImage := image.NewRGBA(image.Rect(0, 0, image_width, image_height))
// set (w)idth and (h)eight. Set h based on w scaled by image ratio
w := 3.0
h := (w * float64(image_height)) / float64(image_width)
// start at negative half the width and height
xmin := -w/2
ymin := -h/2
// maximum number of iterations for each point on the complex plane
// if we dont reach infinty in maxiterations then assume we never will
maxiterations := 100;
// x goes from xmin to xmax
xmax := xmin + w
// y goes from ymin to ymax
ymax := ymin + h
// calculate amount we increment x, y for each pixel
dx := (xmax - xmin) / float64(image_width)
dy := (ymax - ymin) / float64(image_height)
//start y
y := ymin
for j:=0; j < image_height; j++ {
// start x
x := xmin
for i:=0; i < image_width; i++ {
//now we test, as we iteate z = z^2 + cm does z tend towards infinity?
a := x
b := y
n := 0
for n < maxiterations {
aa := a * a
bb := b * b
twoab := 2.0 * a * b
a = aa - bb + x
b = twoab + y
// infintiy in our finite world is simple, let's just consider it 16
if (a*a + b*b) > 16 {
break
}
n++
}
if (n==maxiterations) {
myImage.Set(i, j, color.RGBA{0, 0, 0, 255})
} else {
myImage.Set(i, j, color.RGBA{uint8(n)*16, 0, 0, 255})
}
x += dx
}
y += dy
}
// outputFile is a File type which satisfies Writer interface
outputFile, err := os.Create("test.png")
if err != nil {
// Handle error
}
// Encode takes a writer interface and an image interface
// We pass it the File and the RGBA
png.Encode(outputFile, myImage)
// Don't forget to close files
outputFile.Close()
}