Skip to content

IFS in C #714

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 2 commits into from
Jun 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
Expand Up @@ -132,6 +132,8 @@ Here, instead of tracking children of children, we track a single individual tha
[import:39-52, lang:"cpp"](code/c++/IFS.cpp)
{% sample lang="py" %}
[import:5-12, lang:"python"](code/python/IFS.py)
{% sample lang="c" %}
[import:18-29, lang:"c"](code/c/IFS.c)
{% 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:
Expand Down Expand Up @@ -199,6 +201,8 @@ In addition, we have written the chaos game code to take in a set of points so t
[import, lang:"cpp"](code/c++/IFS.cpp)
{% sample lang="py" %}
[import, lang:"python"](code/python/IFS.py)
{% sample lang="c" %}
[import, lang:"c"](code/c/IFS.c)
{% endmethod %}

### Bibliography
Expand Down
49 changes: 49 additions & 0 deletions contents/IFS/code/c/IFS.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

struct point {
double x, y;
};

double drand() {
return ((double) rand() / (RAND_MAX));
}

struct point random_element(struct point *array, size_t n) {
return array[rand() % (int)n];
}

void chaos_game(struct point *in, size_t in_n, struct point *out,
size_t out_n) {

struct point cur_point = {drand(), drand()};

for (int i = 0; i < out_n; ++i) {
out[i] = cur_point;
struct point tmp = random_element(in, in_n);
cur_point.x = 0.5 * (cur_point.x + tmp.x);
cur_point.y = 0.5 * (cur_point.y + tmp.y);
}
}

int main() {
struct point shape_points [3] = {{0.0,0.0}, {0.5,sqrt(0.75)}, {1.0,0.0}};
struct point out_points[1000];

srand(time(NULL));

chaos_game(shape_points, 3, out_points, 1000);

FILE *fp = fopen("out.dat", "w+");

for (int i = 0; i < 1000; ++i) {
fprintf(fp, "%f\t%f\n", out_points[i].x, out_points[i].y);
}

fclose(fp);

return 0;
}