[Shootout-list] OCaml compilation flags, improved Mandelbrot

Christophe TROESTLER del-con@tiscali.be
Fri, 18 Mar 2005 01:08:45 +0100 (CET)


----Next_Part(Fri_Mar_18_01_08_45_2005_906)--
Content-Type: Text/Plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

On Thu, 17 Mar 2005, Christian Szegedy <szegedy@t-online.de> wrote:
> 
> I coud also improve the speed of the Mandelbrot computation.

Great!

>   tmp.r <- c.r;
>   tmp.i <- c.i;

I believe this is not respecting the spec as the initial point should
be 0. + 0. I -- but simply correcting this changes the image.

I attached a modification of the code that satisfies the requirement
of identical output.

ChriS


--
P.S. May people attach their code with a "text/plain" mime format?  It
makes it easier to see it when searching the archives...

----Next_Part(Fri_Mar_18_01_08_45_2005_906)--
Content-Type: Text/Plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
Content-Disposition: inline; filename="mandelbrot.ml"

let niter = 50
let limit = 2.

let limit2 = limit *. limit

type complex = { mutable r:float; mutable i:float }

let add_bit0 ~tmp:z c byte =
  z.r <- 0.;
  z.i <- 0.;
  try
    for i = 1 to niter do
      let zi = 2. *. z.r *. z.i +. c.i in
      z.r <- z.r *. z.r -. z.i *. z.i +. c.r;
      z.i <- zi;
      if z.r *. z.r +. z.i *. z.i > limit2 then raise Exit;
    done;
    (byte lsl 1) lor 0x01
  with Exit -> (byte lsl 1) lor 0x00

let () =
  let w = int_of_string Sys.argv.(1) in
  let h = w in
  let fw = float w
  and fh = float h
  and cplmt8 = 8 - w mod 8 in
  Printf.printf "P4\n%i %i\n" w h;
  let byte = ref 0
  and bit = ref 0 in
  let c = { r = 0.0; i = 0.0 } in
  let tmp = { r = 0.0; i = 0.0 } in
  for y = 0 to h - 1 do
    c.i <- 2. *. float y /. fh -. 1.;
    for x = 0 to w - 1 do
      c.r <- 2. *. float x /. fw -. 1.5;
      byte := add_bit0 ~tmp c !byte;
      incr bit;
      if !bit = 8 then (
        output_byte stdout !byte;
        byte := 0;
        bit := 0;
      )
    done;
    if !bit <> 0 then (
      output_byte stdout (!byte lsl cplmt8);
      byte := 0;
      bit := 0;
    )
  done

----Next_Part(Fri_Mar_18_01_08_45_2005_906)----