Skip to content

Rust version of IFS #755

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Dec 28, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions contents/IFS/IFS.md
Original file line number Diff line number Diff line change
@@ -136,6 +136,8 @@ Here, instead of tracking children of children, we track a single individual tha
[import:18-29, lang:"c"](code/c/IFS.c)
{% sample lang="coco" %}
[import:4-16, lang:"coconut"](code/coconut/IFS.coco)
{% sample lang="rust" %}
[import:9-20, lang:"rust"](code/rust/IFS.rs)
{% endmethod %}

If we set the initial points to the on the equilateral triangle we saw before, we can see the Sierpinski triangle again after a few thousand iterations, as shown below:
@@ -207,6 +209,8 @@ In addition, we have written the chaos game code to take in a set of points so t
[import, lang:"c"](code/c/IFS.c)
{%sample lang="coco" %}
[import, lang:"coconut"](code/coconut/IFS.coco)
{%sample lang="rust" %}
[import, lang:"rust"](code/rust/IFS.rs)
{% endmethod %}

### Bibliography
36 changes: 36 additions & 0 deletions contents/IFS/code/rust/IFS.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use rand::prelude::*;

#[derive(Clone, Copy)]
struct Point {
x: f64,
y: f64,
}

fn chaos_game(iters: usize, shapes: Vec<Point>) -> Vec<Point> {
let mut rng = rand::thread_rng();
let mut p = Point{x: rng.gen(), y: rng.gen()};

(0..iters).into_iter().map(|_| {
let old_point = p;
let tmp = shapes[rng.gen_range(0, shapes.len())];
p.x = 0.5 * (p.x + tmp.x);
p.y = 0.5 * (p.y + tmp.y);
old_point
}).collect()
}

fn main() {
let shapes = vec![
Point{x: 0., y: 0.},
Point{x: 0.5, y: (0.75 as f64).sqrt()},
Point{x: 1., y: 0.},
];

let mut out = String::new();

for point in chaos_game(10_000, shapes) {
out += format!("{}\t{}\n", point.x, point.y).as_str();
}

std::fs::write("./out.dat", out).unwrap();
}