Skip to content

Instantly share code, notes, and snippets.

@carsten-j
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carsten-j/302720fe715d8cb273b7 to your computer and use it in GitHub Desktop.
Save carsten-j/302720fe715d8cb273b7 to your computer and use it in GitHub Desktop.
MANDELZOOM
open System.Drawing
open System.Numerics
open System.Windows.Forms
// Absolute Square function for complex numbers
type System.Numerics.Complex with
member this.Length = this.Real * this.Real + this.Imaginary * this.Imaginary
// PART ONE: select any square region of the complex plane to be examined.
let title = "Mandelbrot Set"
// Number of rows and columns in the pic array
let rows = 400
let columns = 400
// The coordinates of the southwest corner
let acorner = -2.0 // real part
let bcorner = -1.25 // imaginary part
// Length of each side
let side = 2.5
// PART TWO. adjusts the array pic to match the square of interest
// Distance within the square (determined by the southwest corner and length of each side)
// between each adjacent pixels
let gap = side / float (columns)
let maxIterations = 1000
// PART THREE: the heart of the program. Here a search is made for the
// complex numbers c in the Mandelbrot set, and colors are assigned to the // numbers that are, in a special sense, nearby.
// PART THREE: step 1
// Transforms pixel positions into corresponding complex numbers
let transformPixelPositionToComplexNumber x y =
new Complex((float) x * gap + acorner, (float) y * gap - (bcorner + side))
// PART THREE: step 3
// A point in the complex plane c belong to the Mandelbrot Set
// if the sequence Z(n+1) = Z(n)^2 + c stays bounded.
// By definition Z(0) = 0
let rec MandelbrotSeq (z : Complex) c iterationNumber =
if (z.Length > 4.0) then iterationNumber
else if (iterationNumber = maxIterations) then maxIterations
else
let nextValue = z * z + c
MandelbrotSeq nextValue c (iterationNumber + 1)
// PART THREE: step 4
// Map number of iterations to convergence to a color
let colorMap n maxIterations =
match n with
| n when (n < maxIterations && n > 0) -> mandelbrotColorSchemeWikipedia.[n % 16]
| _ -> Color.FromArgb(0, 0, 0)
/// Returns whether or not the given complex number is in the set to the
/// best possible accuracy we can get from the given number of iterations
let inMandelbrotSet num =
let res = MandelbrotSeq Complex.Zero num 0
colorMap res maxIterations
/// Sets up the canvas and generates the set on it
let generateBitMapWithMandelbrotSet (rows : int) (columns : int) =
let bmp = new Bitmap(rows, columns)
for m in 0..(rows - 1) do
for n in 0..(columns - 1) do
let c = transformPixelPositionToComplexNumber m n
bmp.SetPixel(m, n, (inMandelbrotSet c))
bmp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment