Skip to content

Commit a7a8dfb

Browse files
Add IFS in python (#700)
1 parent 2f06313 commit a7a8dfb

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

CONTRIBUTORS.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,11 @@ This file lists everyone, who contributed to this repo and wanted to show up her
4242
- Christopher Milan
4343
- Vexatos
4444
- Raven-Blue Dragon
45-
- Björn Heinrichs
45+
- Björn Heinrichs
4646
- Olav Sundfør
4747
- Ben Chislett
4848
- dovisutu
4949
- Antetokounpo
5050
- Akash Dhiman
5151
- Vincent Zalzal
52+
- Jonathan D B Van Schenck

contents/IFS/IFS.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,8 @@ Here, instead of tracking children of children, we track a single individual tha
130130
[import:4-17, lang:"julia"](code/julia/IFS.jl)
131131
{% sample lang="cpp" %}
132132
[import:39-52, lang:"cpp"](code/c++/IFS.cpp)
133+
{% sample lang="py" %}
134+
[import:5-12, lang:"python"](code/python/IFS.py)
133135
{% endmethod %}
134136

135137
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:
@@ -195,6 +197,8 @@ In addition, we have written the chaos game code to take in a set of points so t
195197
[import, lang:"julia"](code/julia/IFS.jl)
196198
{% sample lang="cpp" %}
197199
[import, lang:"cpp"](code/c++/IFS.cpp)
200+
{% sample lang="py" %}
201+
[import, lang:"python"](code/python/IFS.py)
198202
{% endmethod %}
199203

200204
### Bibliography

contents/IFS/code/python/IFS.py

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

0 commit comments

Comments
 (0)