開発環境
- 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.8の解答を求めてみる。
コード
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
)
img1 := image.NewRGBA(image.Rect(0, 0, width, height))
for py := 0; py < height; py++ {
y := float32(py)/height*(ymax-ymin) + ymin
for px := 0; px < width; px++ {
x := float32(px)/width*(xmax-xmin) + xmin
z := complex64(complex(x, y))
img1.Set(px, py, newton1(z))
}
}
file1, err := os.Create("sample8_1.png")
if err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(1)
}
defer file1.Close()
err = png.Encode(file1, img1)
if err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(1)
}
img2 := 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)
img2.Set(px, py, newton2(z))
}
}
file2, err := os.Create("sample8_2.png")
if err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(1)
}
defer file2.Close()
err = png.Encode(file2, img2)
if err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(1)
}
}
const (
iterations = 200
contrast = 15
epsilon = 0.1
)
func newton1(z complex64) color.Color {
guess := z
for n := uint8(0); n < iterations; n++ {
v := guess * guess * guess * guess
if math.Abs(float64(real(v))-1) < epsilon &&
math.Abs(float64(imag(v))) < epsilon {
return color.Gray{255 - contrast*n}
}
guess = (guess + 1/(guess*guess*guess)) / 2
}
return color.Black
}
func newton2(z complex128) color.Color {
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 {
return color.Gray{255 - contrast*n}
}
guess = (guess + 1/cmplx.Pow(guess, 3)) / 2
}
return color.Black
}
入出力結果(cmd(コマンドプロンプト)、Terminal)
C:\Users\...> go run sample8.go C:\Users\...>
math/bigパッケージのFloat型、Rat型については、試したものの計算に時間がかかったので中断。あと、インタフェースを使用しないで複素数を実装から、いずれインターフェースを利用して実装して試すことに。


0 コメント:
コメントを投稿