-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnewton-fractal.go
92 lines (77 loc) · 2.28 KB
/
newton-fractal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package newton_fractal
import (
"image"
"image/color"
"math/cmplx"
)
var Palette = []color.Color{
color.RGBA{0, 0, 0, 255},
color.RGBA{85, 65, 95, 255},
color.RGBA{100, 105, 100, 255},
color.RGBA{215, 115, 85, 255},
color.RGBA{80, 140, 215, 255},
color.RGBA{100, 185, 100, 255},
color.RGBA{230, 200, 110, 255},
color.RGBA{220, 245, 255, 255},
}
// NewtonFunc(x) returns the step computed by Newton's method
func NewtonFunc(x complex128) complex128 {
// The polynomial equation for the fractal is x^8 - 1 = 0
xSeventh := x * x * x * x * x * x * x
xEigth := xSeventh * x // d/dx(x^8 - 1) = 8x^7
// Implementing Newton's method: xn - f(xn)/f'(xn)
return x - (xEigth-1)/(8.0*xSeventh)
}
/* GenerateFractal(bottomLeft, topRight) generates a 960 by 540 image of the fractal within a "space" on the complex plane
specified by a bottom left point and a top right point
*/
func GenerateFractal(bottomLeft complex128, topRight complex128) *image.RGBA {
realStep := (real(topRight) - real(bottomLeft)) / float64(640)
imagStep := (imag(topRight) - imag(bottomLeft)) / float64(480)
out := image.NewRGBA(image.Rect(0, 0, 640, 480))
for i := 0; i < 640; i++ {
rc := real(bottomLeft) + realStep*float64(i)
for j := 0; j < 480; j++ {
ic := imag(bottomLeft) + imagStep*float64(j)
color := getColor128(complex(rc, ic))
out.Set(i, j, color)
}
}
return out
}
func getColor128(p complex128) color.Color {
roots := [8]complex128{
1.0 + 0.0i,
-1.0 + 0.0i,
0.0 + 1.0i,
0.0 - 1.0i,
0.70710678118 + 0.70710678118i,
-0.70710678118 - 0.70710678118i,
0.70710678118 - 0.70710678118i,
-0.70710678118 + 0.70710678118i,
}
const epsilon = 0.00001
pv := NewtonFunc(p)
for iterations := uint(1); iterations < 100; iterations++ {
switch {
case cmplx.Abs(pv-roots[0]) < epsilon:
return Palette[0]
case cmplx.Abs(pv-roots[1]) < epsilon:
return Palette[1]
case cmplx.Abs(pv-roots[2]) < epsilon:
return Palette[2]
case cmplx.Abs(pv-roots[3]) < epsilon:
return Palette[3]
case cmplx.Abs(pv-roots[4]) < epsilon:
return Palette[4]
case cmplx.Abs(pv-roots[5]) < epsilon:
return Palette[5]
case cmplx.Abs(pv-roots[6]) < epsilon:
return Palette[6]
case cmplx.Abs(pv-roots[7]) < epsilon:
return Palette[7]
}
pv = NewtonFunc(pv)
}
return color.RGBA{0, 0, 0, 255}
}