Skip to content

Commit f0b388f

Browse files
authored
IFS in coconut (#727)
1 parent 78171e0 commit f0b388f

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -511,3 +511,6 @@ vscode/
511511

512512
# Data file extension for Algorithm Archive
513513
*.dat
514+
515+
# Coconut compilation files
516+
**/coconut/*.py

contents/IFS/IFS.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,8 @@ Here, instead of tracking children of children, we track a single individual tha
134134
[import:5-12, lang:"python"](code/python/IFS.py)
135135
{% sample lang="c" %}
136136
[import:18-29, lang:"c"](code/c/IFS.c)
137+
{% sample lang="coco" %}
138+
[import:4-16, lang:"coconut"](code/coconut/IFS.coco)
137139
{% endmethod %}
138140

139141
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:
@@ -203,6 +205,8 @@ In addition, we have written the chaos game code to take in a set of points so t
203205
[import, lang:"python"](code/python/IFS.py)
204206
{% sample lang="c" %}
205207
[import, lang:"c"](code/c/IFS.c)
208+
{%sample lang="coco" %}
209+
[import, lang:"coconut"](code/coconut/IFS.coco)
206210
{% endmethod %}
207211

208212
### Bibliography

contents/IFS/code/coconut/IFS.coco

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from math import sqrt
2+
from random import random, choice
3+
4+
data point(x=0, y=0):
5+
def __add__(self, other):
6+
return point(self.x + other.x, self.y + other.y)
7+
8+
def __rmul__(self, other):
9+
return point(self.x * other, self.y * other)
10+
11+
def chaos_game(n, shape_points):
12+
p = point(random(), random())
13+
14+
for _ in range(n):
15+
p = (1/2) * (p + choice(shape_points))
16+
yield p
17+
18+
19+
# This will generate a Sierpinski triangle with a chaos game of n points for an
20+
# initial triangle with three points on the vertices of an equilateral triangle:
21+
# A = (0.0, 0.0)
22+
# B = (0.5, sqrt(0.75))
23+
# C = (1.0, 0.0)
24+
# It will output the file sierpinski.dat, which can be plotted after
25+
shape_points = [point(0.0, 0.0),
26+
point(0.5, sqrt(0.75)),
27+
point(1.0, 0.0)]
28+
with open("sierpinski.dat", "w") as f:
29+
for p in chaos_game(10000, shape_points):
30+
f.write("{0}\t{1}\n".format(p.x, p.y))

0 commit comments

Comments
 (0)