開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Go (プログラミング言語)
プログラミング言語Go (ADDISON-WESLEY PROFESSIONAL COMPUTING SERIES) (Alan A.A. Donovan(著)、Brian W. Kernighan(著)、柴田 芳樹(翻訳)、丸善出版)の第3章(基本データ型)、3.3(複素数)、練習問題3.5の解答を求めてみる。
コード
package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math/cmplx"
"os"
)
func main() {
const (
xmin, ymin, xmax, ymax = -2, -2, 2, 2
width, height = 512, 512
)
img := image.NewRGBA(image.Rect(0, 0, width, height))
for py := 0; py < height; py++ {
y := float64(py)/height*(ymax-ymin) + ymin
for px := 0; px < width; px++ {
x := float64(px)/width*(xmax-xmin) + xmin
z := complex(x, y)
img.Set(px, py, mandelbrot(z))
}
}
file, err := os.Create("sample5.png")
if err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(1)
}
defer file.Close()
err = png.Encode(file, img)
if err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(1)
}
fmt.Printf("赤系: %d, 緑系: %d, 青系: %d\n", nRed, nGreen, nBlue)
}
var (
nRed = 0
nGreen = 0
nBlue = 0
)
func mandelbrot(z complex128) color.Color {
const (
interations = 200
contrast = 15
)
var v complex128
for n := uint8(0); n < interations; n++ {
v = v*v + z
if cmplx.Abs(v) > 2 {
if n%3 == 0 {
nRed++
return color.RGBA{255 - contrast*n, 0, 0, 255}
} else if n%3 == 1 {
nGreen++
return color.RGBA{0, 255 - contrast*n, 0, 255}
} else {
nBlue++
return color.RGBA{0, 0, 255 - contrast*n, 255}
}
}
}
return color.Black
}
入出力結果(cmd(コマンドプロンプト)、Terminal)
C:\Users\...> go run sample5.go 赤系: 77164, 緑系: 116386, 青系: 43501 C:\Users\...>
0 コメント:
コメントを投稿