-
-
Save CrazyPython/8bafd16837ec8ad4c5a638b9d305fc96 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
import std.stdio; | |
import std.math; | |
import core.time; | |
class Complex { | |
double x; | |
double y; | |
this(A)(A px, A py) { | |
this.x = px; | |
this.y = py; | |
} | |
unittest { | |
auto complex = new Complex(2, 2); | |
assert(complex.x == 2 && complex.y == 2); | |
} | |
auto abs() const { | |
return fmax(this.x * this.x, this.y * this.y); | |
} | |
void add(T)(const T other) { | |
this.x += other.x; | |
this.y += other.y; | |
} | |
void mul(T)(const T other) { | |
auto newX = this.x * other.x - this.y * other.y; | |
auto newY = this.x * other.y + this.y * other.x; | |
this.x = newX; | |
this.y = newY; | |
} | |
} | |
unittest { | |
auto c = new Complex(5, 3); | |
c.mul(new Complex(4, 2)); | |
assert(c.x == 14 && c.y == 22); | |
} | |
unittest { | |
auto org = new Complex(0, 0); | |
org.add(new Complex(3, 3)); | |
assert(org.x == 3 && org.y == 3); | |
} | |
auto iterate_mandelbrot(const Complex c, const int maxIters) { | |
auto z = new Complex(0, 0); | |
for (int i = 0; i < maxIters; i++) { | |
if (z.abs() >= 2.0) { | |
return i; | |
} | |
z.mul(z); | |
z.add(c); | |
} | |
return maxIters; | |
} | |
const x0 = -2.5, x1 = 1, y0 = -1, y1 = 1; | |
const cols = 72, rows = 24; | |
const maxIters = 1000000; | |
void main() { | |
auto now = MonoTime.currTime; | |
for (double row = 0; row < rows; row++) { | |
const y = (row / rows) * (y1 - y0) + y0; | |
char[] str; | |
for (double col = 0; col < cols; col++) { | |
// double is needed here because otherwise "/" does integer division | |
const x = (col / cols) * (x1 - x0) + x0; | |
auto c = new Complex(x, y); | |
auto iters = iterate_mandelbrot(c, maxIters); | |
if (iters == 0) { | |
str ~= '.'; | |
} else if (iters == 1) { | |
str ~= '%'; | |
} else if (iters == 2) { | |
str ~= '@'; | |
} else if (iters == maxIters) { | |
str ~= ' '; | |
} else { | |
str ~= '#'; | |
} | |
} | |
str.writeln; | |
} | |
writeln(MonoTime.currTime - now); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment