Created
December 2, 2016 20:30
-
-
Save jpouellet/be623ec65420f62d812a96db423283a9 to your computer and use it in GitHub Desktop.
Python mandelbrot set generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| import argparse | |
| import sys | |
| import os | |
| trace = False | |
| def pixel_n(x0, y0, escape): | |
| x=0. | |
| y=0. | |
| for i in xrange(escape): | |
| x2 = x*x | |
| y2 = y*y | |
| if x2 + y2 > 2*2: | |
| return (True, i) | |
| x, y = x2 - y2 + x0, 2*x*y + y0 | |
| if trace: print (x0, y0, i, x, y) | |
| return (False, escape) | |
| def pixel(x0, y0, escape, xmin, xmax, ymin, ymax): | |
| clamp = lambda val, low, high: val * (high - low) + low | |
| return pixel_n(clamp(x0, xmin, xmax), clamp(y0, ymin, ymax), escape) | |
| def mandel(w, h, escape, xmin=-2.5, xmax=1., ymin=-1., ymax=1.): | |
| return [[pixel(float(x)/w, float(y)/h, escape, xmin, xmax, ymin, ymax) | |
| for x in xrange(w)] for y in xrange(h)] | |
| def pixel_s(px): | |
| escapes, at = px | |
| if escapes: | |
| return "%3d" % at | |
| return " " | |
| def mandel_s(m): | |
| return '\n'.join(' '.join(pixel_s(px) for px in line) for line in m) | |
| def main(): | |
| ap = argparse.ArgumentParser(description="Mandelbrot set generator") | |
| ap.add_argument('--width', type=int) | |
| ap.add_argument('--height', type=int) | |
| ap.add_argument('--xmin', type=float, default=-2.5) | |
| ap.add_argument('--xmax', type=float, default=1.) | |
| ap.add_argument('--ymin', type=float, default=-1.) | |
| ap.add_argument('--ymax', type=float, default=1.) | |
| ap.add_argument('--escape', type=int, default=99) | |
| ap.add_argument('--trace', action='store_true') | |
| a = ap.parse_args() | |
| trace = a.trace | |
| th, tw = os.popen('stty size', 'r').read().split() | |
| w = a.width or (int(tw) or 80)/4 | |
| h = a.height or (int(th) or 24)-1 | |
| if trace: print (h, w, a.escape, a.xmin, a.xmax, a.ymin, a.ymax) | |
| print mandel_s(mandel(w=w, h=h, escape=a.escape, | |
| xmin=a.xmin, xmax=a.xmax, ymin=a.ymin, ymax=a.ymax)) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment