Skip to content

Commit 0f0437b

Browse files
authored
IFS in C (#714)
* Add IFS.c * Updating IFS.md
1 parent 574c85f commit 0f0437b

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

contents/IFS/IFS.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,8 @@ Here, instead of tracking children of children, we track a single individual tha
132132
[import:39-52, lang:"cpp"](code/c++/IFS.cpp)
133133
{% sample lang="py" %}
134134
[import:5-12, lang:"python"](code/python/IFS.py)
135+
{% sample lang="c" %}
136+
[import:18-29, lang:"c"](code/c/IFS.c)
135137
{% endmethod %}
136138

137139
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:
@@ -199,6 +201,8 @@ In addition, we have written the chaos game code to take in a set of points so t
199201
[import, lang:"cpp"](code/c++/IFS.cpp)
200202
{% sample lang="py" %}
201203
[import, lang:"python"](code/python/IFS.py)
204+
{% sample lang="c" %}
205+
[import, lang:"c"](code/c/IFS.c)
202206
{% endmethod %}
203207

204208
### Bibliography

contents/IFS/code/c/IFS.c

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include <math.h>
2+
#include <stdio.h>
3+
#include <stdlib.h>
4+
#include <time.h>
5+
6+
struct point {
7+
double x, y;
8+
};
9+
10+
double drand() {
11+
return ((double) rand() / (RAND_MAX));
12+
}
13+
14+
struct point random_element(struct point *array, size_t n) {
15+
return array[rand() % (int)n];
16+
}
17+
18+
void chaos_game(struct point *in, size_t in_n, struct point *out,
19+
size_t out_n) {
20+
21+
struct point cur_point = {drand(), drand()};
22+
23+
for (int i = 0; i < out_n; ++i) {
24+
out[i] = cur_point;
25+
struct point tmp = random_element(in, in_n);
26+
cur_point.x = 0.5 * (cur_point.x + tmp.x);
27+
cur_point.y = 0.5 * (cur_point.y + tmp.y);
28+
}
29+
}
30+
31+
int main() {
32+
struct point shape_points [3] = {{0.0,0.0}, {0.5,sqrt(0.75)}, {1.0,0.0}};
33+
struct point out_points[1000];
34+
35+
srand(time(NULL));
36+
37+
chaos_game(shape_points, 3, out_points, 1000);
38+
39+
FILE *fp = fopen("out.dat", "w+");
40+
41+
for (int i = 0; i < 1000; ++i) {
42+
fprintf(fp, "%f\t%f\n", out_points[i].x, out_points[i].y);
43+
}
44+
45+
fclose(fp);
46+
47+
return 0;
48+
}
49+

0 commit comments

Comments
 (0)