Skip to content

Instantly share code, notes, and snippets.

@tatyusa
Last active January 2, 2016 08:39
Show Gist options
  • Save tatyusa/8278212 to your computer and use it in GitHub Desktop.
Save tatyusa/8278212 to your computer and use it in GitHub Desktop.
Goでフラクタルを書いてみました。 各点がFatou集合に入ってるかどうかを並列に計算する単純なものです。 結果は同じフォルダに"result.png"として出力されます。
package main
import (
"fmt"
"math/cmplx"
"image"
"image/png"
"os"
)
// 生成する画像の大きさと解像度
const width = 800
const height = 800
const scale = 200
const infty = 1000000.0
const max_iterate = 50
func f(z complex128) complex128 {
return z*z + complex(-0.765,0.12)
}
func inFatou(z complex128) bool{
for i:=0;i<max_iterate;i++ {
z = f(z)
if cmplx.Abs(z)>infty { return true }
}
return false
}
func main(){
points := width * height
// 画像の生成と初期化
fmt.Println("Calclating Julia Set")
img := image.NewGray(image.Rect(0,0,width,height))
c := make(chan int, points)
for x:=0;x<width;x+=1 {
for y:=0;y<height;y+=1 {
go func(x,y int, c chan int){
z := pixelToComplex(x,y)
if inFatou(z) {
img.Pix[y*width + x] = 255
}else{
img.Pix[y*width + x] = 0
}
c <- 1
}(x,y,c)
}
}
for i := 0; i<points; i++ {
<-c
}
// 画像出力
fmt.Println("Making Result...")
file, err := os.Create("result.png")
if err != nil {
panic(err)
}
defer file.Close()
png.Encode(file, img)
if err != nil {
panic(err)
}
}
func pixelToComplex(x,y int) complex128 {
return complex(float64(x-width/2)/float64(scale),float64(y-height/2)/float64(scale))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment