開発環境
- 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.7の解答を求めてみる。
コード
package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"math/cmplx"
"os"
)
func main() {
const (
xmin, ymin, xmax, ymax = -2, -2, 2, 2
// width, height = 1024, 1024
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, newton(z))
}
}
file, err := os.Create("sample7.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、黄 %d、黒 %d\n",
redCount, greenCount, blueCount, yelloCount, blackCount)
}
var (
redCount = 0
greenCount = 0
blueCount = 0
yelloCount = 0
blackCount = 0
)
func newton(z complex128) color.Color {
const (
iterations = 200
contrast = 15
epsilon = 0.1
)
guess := z
for n := uint8(0); n < iterations; n++ {
v := cmplx.Pow(guess, 4)
if math.Abs(real(v)-1) < epsilon && math.Abs(imag(v)) < epsilon {
var c color.RGBA
if real(guess) > 0 && math.Abs(imag(guess)) < epsilon {
c = color.RGBA{255 - contrast*n, 0, 0, 255}
redCount++
} else if real(guess) < 0 && math.Abs(imag(guess)) < epsilon {
c = color.RGBA{0, 255 - contrast*n, 0, 255}
greenCount++
} else if imag(guess) > 0 {
c = color.RGBA{0, 0, 255 - contrast*n, 255}
blueCount++
} else {
c = color.RGBA{255 - contrast*n, 255 - contrast*n, 0, 255}
yelloCount++
}
return c
}
guess = (guess + 1/cmplx.Pow(guess, 3)) / 2
}
blueCount++
return color.Black
}
入出力結果(cmd(コマンドプロンプト)、Terminal)
C:\Users\...> go run sample7.go 赤 61370、 緑 61617、青 77534、黄 61623、黒 0 C:\Users\...>
0 コメント:
コメントを投稿