/
julia.go
100 lines (74 loc) · 2.47 KB
/
julia.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
93
94
95
96
97
98
99
100
package main
import (
"fmt"
"math"
"strconv"
)
// A Julia represents the strongly typed planar space for a Julia fractal
type juliaPlane struct {
Plane
}
func newJulia() juliaPlane {
return juliaPlane{Plane{-2.0, 2.0, -2.0, 2.0}}
}
func (m *juliaPlane) process(c config) {
if c.midX == -99.0 {
c.midX = (m.rMax + m.rMin) / 2.0
}
if c.midY == -99.0 {
c.midY = (m.iMax + m.iMin) / 2.0
}
if c.mode == imageMode {
m.image(c)
} else if c.mode == coordinatesMode {
var r, i = m.calculateCoordinatesAtPoint(c)
fmt.Printf("%18.17e, %18.17e\n", r, i)
}
}
func (m *juliaPlane) image(c config) {
initialiseGradient(c.gradient)
c.bailout = determineJuliaBailout(c)
mbi := initialiseimage(c)
plottedChannel := make(chan PlottedPoint)
go func(points <-chan PlottedPoint) {
for p := range points {
if p.Escaped {
mbi.Set(p.X, p.Y, getPixelColour(p, c.maxIterations, c.colourMode))
}
}
}(plottedChannel)
var checkIfPointEscapes escapeCalculator = func(real float64, imag float64, config config) (bool, int, float64, float64) {
var iteration int
zR := real
zI := imag
for iteration = 0.0; zR*zR+zI*zI < config.bailout && iteration < config.maxIterations; iteration++ {
tmp := zR*zR - zI*zI
zI = 2*zR*zI + config.constI
zR = tmp + config.constR
}
return iteration < config.maxIterations, iteration, zR, zI
}
m.iterateOverPoints(c, plottedChannel, checkIfPointEscapes)
if c.filename == "" {
c.filename = "julia_" + strconv.FormatFloat(c.midX, 'E', -1, 64) + "_" + strconv.FormatFloat(c.midY, 'E', -1, 64) + "_" + strconv.FormatFloat(c.zoom, 'E', -1, 64) + ".jpg"
}
saveimage(mbi, c.output, c.filename)
fmt.Printf("%s/%s\n", c.output, c.filename)
}
func determineJuliaBailout(config config) float64 {
/* Where c is the constant in the Julia algorithim, expressed as a complex number,
Bailout should be R where R**2 - R = |c|.
That's the quadratic equation, which will give us two values. We'll take the larger.
*/
cAbs := math.Sqrt(config.constR*config.constR + config.constI*config.constI)
a, b := quadratic(1.0, -1.0, -1.0*cAbs)
/* The bailout test will be testing against the square of R anyway, so doing it now saves
messing about with absolute values of the returns from the quadratic formula */
return max(a*a, b*b)
}
func quadratic(a float64, b float64, c float64) (float64, float64) {
// 0 = ax**2 + bx + c
// x = (-b ± sqrt(b**2 - 4ac)) / 2a
d := math.Sqrt(b*b - 4*a*c)
return (-1.0*b + d) / 2.0 * a, (-1.0*b - d) / 2.0 * a
}