caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* Random questions
@ 2009-11-18 10:59 Daniel Bünzli
  2009-12-03 11:00 ` [Caml-list] " AUGER
  0 siblings, 1 reply; 6+ messages in thread
From: Daniel Bünzli @ 2009-11-18 10:59 UTC (permalink / raw)
  To: caml-list

I know little about PRGN and unfortunately in a lot of cases the
functions in the Random module don't provide me the right
interface. Could anybody tell me if the following functions preserve
the quality of the underlying PRGN and/or if there's a better way to
achieve that :

1) Generate an arbitrary int

let rint () = Random.bits () lor ((Random.bits () land 1) lsl 30)


2) Generate an arbitrary int in [0;max] (bounds included)

let random_uint ?(max = max_int) =
  if max < 0 then invalid_arg "negative max" else
  if max = max_int then Random.bits else
  let bound = max + 1 in
  fun () -> Random.int bound


3) Generate an arbitrary int in [-max;max] (bounds included)

let random_int ?(max = max_int) =
  if max < 0 then invalid_arg "negative max" else
  if max = max_int then
    let rec aux () =
      let v = rint () in if v = min_int then aux () else v in
      aux
  else
    let bound = (2 * max) + 1 in
    if 0 < bound && bound < max_int then
      fun () -> -max + Random.int bound
    else
      let bound = Int32.add (Int32.mul 2l (Int32.of_int max)) 1l in
      let min = Int32.of_int (-max) in
      fun () -> Int32.to_int (Int32.add min (Random.int32 bound))


5) Generate an arbitrary float in [0;max] (bounds included)

let after_one = 1. +. epsilon_float
let random_ufloat ?(max = max_float) =
  if max < 0. then invalid_arg "negative max" else
  fun () -> (Random.float after_one) *. max


6) Generate an arbitrary float in [-max;max] (bounds included)

let after_one = 1. +. epsilon_float
let random_float ?(max = max_float) =
  if max < 0. then invalid_arg "negative max" else
  fun () -> (-1. +. (Random.float after_one) *. 2.) *. max


Thanks for your answers,

Daniel


^ permalink raw reply	[flat|nested] 6+ messages in thread

end of thread, other threads:[~2009-12-03 16:45 UTC | newest]

Thread overview: 6+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2009-11-18 10:59 Random questions Daniel Bünzli
2009-12-03 11:00 ` [Caml-list] " AUGER
2009-12-03 14:48   ` Daniel Bünzli
2009-12-03 15:11     ` AUGER
2009-12-03 16:01   ` Damien Doligez
2009-12-03 16:45     ` AUGER

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).