Skip to content

Instantly share code, notes, and snippets.

@Mr-Slippery
Last active April 5, 2020 16:27
Show Gist options
  • Save Mr-Slippery/dc04877c05c5973f4bd83fcd02502a63 to your computer and use it in GitHub Desktop.
Save Mr-Slippery/dc04877c05c5973f4bd83fcd02502a63 to your computer and use it in GitHub Desktop.
ASCII rendering of Mandelbrot in Rust
extern crate num;
use num::complex::Complex;
struct IFS
{
max_iter: u64
}
trait DDS<State> {
fn cont(&self, z: State) -> bool;
fn next(&self, z: State, c: State) -> State;
}
impl DDS<Complex<f64>> for IFS {
fn cont(&self, z: Complex<f64>) -> bool {
z.norm_sqr() <= 4.0
}
fn next(&self, z: Complex<f64>, c: Complex<f64>) -> Complex<f64> {
z * z + c
}
}
impl IFS
{
pub fn new(max_iter: u64) -> Self {
Self {
max_iter: max_iter
}
}
pub fn iter(&self, c: Complex<f64>) -> u64 {
let mut i: u64 = 0;
let mut z = c;
while i < self.max_iter && self.cont(z) {
z = self.next(z, c);
i += 1;
}
if i < self.max_iter { return self.max_iter - i; }
0
}
}
fn main() {
let min = Complex::new(-2.0, -2.0);
let max = Complex::new(2.0, 2.0);
let d_x = 80;
let d_y = 50;
let mandel = IFS::new(256);
for j in 0..d_y-1 {
for i in 0..d_x-1 {
let x = min.re + (max.re - min.re) * (i as f64) / (d_x as f64);
let y = min.im + (max.im - min.im) * (j as f64) / (d_y as f64);
let c = Complex::new(x, y);
let m = mandel.iter(c);
let mut ch = ' ';
if m > 0 && m < 64 {
ch = '.';
}
if m >= 64 && m < 128 {
ch = 'o';
}
if m >= 128 && m < 192 {
ch = '*';
}
if m >= 192 && m < 256 {
ch = '0';
}
print!("{}", ch);
}
println!("")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment