[Shootout-list] Mabdelbrot (OCaml)

Christophe TROESTLER Christophe.Troestler at umh.ac.be
Sun Apr 23 22:57:08 UTC 2006


Hi,

Here is an implementation of the mandelbrot test for OCaml.

ChriS
-------------- next part --------------
(* http://shootout.alioth.debian.org/benchmark.php?test=mandelbrot&lang=all *)
(* Plot the Mandelbrot set [-1.5-i,0.5+i] on an N-by-N bitmap
(http://www-info2.informatik.uni-wuerzburg.de/mitarbeiter/wolfram/lehre/bildformate.html#pbm). *)

let niter = 50
let limit = 2.

let limit2 = limit *. limit

let add_bit0 cr ci byte =
  let rec loop i zr zi =
    if i > niter then (byte lsl 1) lor 0x01
    else if zr *. zr +. zi *. zi > limit2 then (byte lsl 1) lor 0x00
    else loop (succ i) (zr *. zr -. zi *. zi +. cr) (2. *. zr *. zi +. ci) in
  loop 1 0. 0.

let () =
  let w = int_of_string Sys.argv.(1) in
  let h = w in
  let invw = 2. /. float w
  and invh = 2. /. float h
  and cplmt8 = let w8 = w mod 8 in if w8 = 0 then 0 else 8 - w8 in
  Printf.printf "P4\n%i %i\n" w h;
  let byte = ref 0
  and bit = ref 0 in
  for y = 0 to h - 1 do
    let ci = float y *. invh -. 1. in
    for x = 0 to w - 2 do
      byte := add_bit0 (float x *. invw -. 1.5) ci !byte;
      incr bit;
      if !bit = 8 then (
	output_byte stdout !byte;
	byte := 0;
	bit := 0;
      )
    done;
    output_byte stdout (!byte lsl cplmt8);
    byte := 0;
    bit := 0;
  done


More information about the Shootout-list mailing list