#!/usr/bin/env python # 2017-02-12 Simple IFS example # http://algoristo.com/teaching/ # http://archive.bridgesmathart.org/2016/bridges2016-533.html\ import math from random import random, choice ninit = 10000 niter = 10 def rotate(x, y, degrees): s = math.sin(math.pi*degrees/180) c = math.cos(math.pi*degrees/180) return c*x - s*y, c*y + s*x # Example: Koch snowflake def k1(x, y): return x/3, y/3 def k2(x, y): return x/3 + 2.0/3, y/3 def k3(x, y): x, y = rotate(x, y, 60) return x/3 + 1.0/3, y/3 def k4(x, y): x, y = rotate(x, y, -60) return x/3 + 0.5, y/3 + math.sqrt(3)/6 ifs = [k1, k2, k3, k4] # Save all stages datfiles = [] for n in range(niter + 1): datfiles.append(open("ifs%i.dat" % n, "w")) for i in range(1, ninit + 1): # Random point x = random() y = random() # Save the initial set datfiles[0].write("%f %f\n" % (x, y)) for j in range(1, niter + 1): f = choice(ifs) x, y = f(x, y) datfiles[j].write("%f %f\n" % (x, y)) for dat in datfiles: dat.close()