Skip to content

Instantly share code, notes, and snippets.

@CrazyPython
Created August 26, 2020 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CrazyPython/3552e1405dbb4b640810f6443cd0a015 to your computer and use it in GitHub Desktop.
Save CrazyPython/3552e1405dbb4b640810f6443cd0a015 to your computer and use it in GitHub Desktop.
class Complex {
constructor(x, y) {
this.x = x;
this.y = y;
}
abs() {
return Math.max(this.x * this.x, this.y * this.y);
//return Math.sqrt(this.x * this.x, this.y * this.y);
//return Math.hypot(this.x, this.y);
}
add(other) {
this.x += other.x;
this.y += other.y;
}
mul(other) {
let newX = this.x * other.x - this.y * other.y;
let newY = this.x * other.y + this.y * other.x;
this.x = newX;
this.y = newY;
}
}
//Object.freeze(Complex);
// z(n+1) = z(n)^2 + c
function iterate_mandelbrot(c, maxIters) {
const z = new Complex(0, 0);
for (let i = 0; i < maxIters; i++) {
if (z.abs() >= 2) {
return i;
}
z.mul(z);
z.add(c);
if (i !== 0)
quit();
}
return maxIters;
}
function main() {
const start = Date.now();
const x0 = -2.5, x1 = 1, y0 = -1, y1 = 1;
const cols = 72, rows = 24;
const maxIters = 1000000;
for (let row = 0; row < rows; row++) {
const y = (row / rows) * (y1 - y0) + y0;
let str = '';
for (let col = 0; col < cols; col++) {
const x = (col / cols) * (x1 - x0) + x0;
const c = new Complex(x, y);
const 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 += '#';
}
}
console.log(str);
}
let end = Date.now() - start;
console.log(end, 'milliseconds runtime');
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment