User:Vel!/tetrationfractal.py

Here is a Python script that draws an infinite tetration fractal.


 * 1) !/usr/bin/env python3.2

import math import colorsys

ITERATIONS = 50
 * 1) Iterations for the fractal

ESCAPE_RADIUS = 100
 * 1) Escape radius

BOUNDING_BOX = -5 - 3j, 5 + 3j
 * 1) Tuple of upper left and lower right corners

SCALE = 100
 * 1) Number of pixels per unit square

def tetra(c): """Return -1 if infinite tetration on c is convergent. Otherwise, return the number of iterations needed to escape..""" z = 1 + 0j for i in range(ITERATIONS): z = c ** z       if abs(z) > ESCAPE_RADIUS: return i    return -1

def iterhue(i): """Convert an iteration count into a hue.""" # Algorithm loosely derived from http://mrob.com/pub/muency/color.html h = math.log(i + 3, 2) + 0.5 if i % 2 == 1: h += 0.05 return h % 1

hues = [iterhue(i) for i in range(ITERATIONS)]
 * 1) Precompute some hues

def color(i): """Get a color given an iteration count.""" if i == -1: r, g, b = 0, 0, 0 else: r, g, b = colorsys.hsv_to_rgb(hues[i], 1.0, 1.0) r, g, b = int(r * 255), int(g * 255),int(b * 255) return "{} {} {} ".format(r, g, b)

b1, b2 = BOUNDING_BOX xoff, yoff = b1.real, b1.imag xext, yext = abs((b2 - b1).real), abs((b2 - b1).imag) w, h = int(SCALE * xext), int(SCALE * yext)

f = open("fractal.ppm", "w") f.write("P3 {} {} 255\n".format(w, h))

for y in range(h): for x in range(w): c = (xoff + x / SCALE) - (yoff + y / SCALE) * 1j i = tetra(c) f.write(color(i)) f.write("\n")

f.close

This Python code produces the following output:



The output file is a PPM, a notoriously inefficient file format. I use it only because I was too lazy to use a proper image library.