home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #20 / NN_1992_20.iso / spool / comp / lang / function / 1067 < prev    next >
Encoding:
Text File  |  1992-09-08  |  1.8 KB  |  53 lines

  1. Newsgroups: comp.lang.functional
  2. Path: sparky!uunet!munnari.oz.au!manuel!newshost.anu.edu.au!lambert
  3. From: lambert@spectrum.cs.unsw.oz.au (Tim Lambert)
  4. Subject: Re: Random number generator for Haskell (wanted)
  5. In-Reply-To: waugh@probitas.cs.utas.edu.au's message of Mon, 7 Sep 1992 00:53:03 GMT
  6. Message-ID: <LAMBERT.92Sep7192624@nankeen.spectrum.cs.unsw.oz.au>
  7. Sender: news@newshost.anu.edu.au
  8. Organization: CS&E, Uni of NSW, Australia
  9. References: <bruce.715827183@probitas>
  10. Date: 7 Sep 92 19:26:24
  11. Lines: 40
  12.  
  13. >>>>> On Mon, 7 Sep 1992 00:53:03 GMT, waugh@probitas.cs.utas.edu.au (Sam Waugh) said:
  14.  
  15. > I was wondering if anybody has implemented a random number generator
  16. > in Haskell?  I am trying to use Haskell for some neural network
  17. > applications and definitely need a good random function.  Otherwise
  18.  
  19. Here is one I wrote in Miranda (you didn't say if you wanted uniform
  20. or normal variates, so I give you both.)
  21.  
  22. Tim
  23.  
  24. >|| random.m
  25.  
  26. random is given a positive integer seed and returns an infinite list
  27. of uniform random numbers between 0 and 1.  We use a linear
  28. congruential generator (see "Art of Computer Programming Vol 2")
  29.  
  30. > random :: num -> [num]
  31. > random = map (/modulus) . iterate f
  32. >          where f x = (x*multiplier) mod modulus
  33. > multiplier = 69069
  34. > modulus = 2^32
  35.  
  36. normal_random is given a seed and returns an infinite list of random
  37. normal variates with mean 0 and variance 1.  (Box Muller method see
  38. "Art of Computer Programming Vol 2")
  39.  
  40. > normal_random :: num -> [num]
  41. > normal_random = box_muller.(map f).random
  42. >          where f x = 2*x - 1
  43.  
  44. box_muller takes a stream of uniform random numbers on [-1,1] and
  45. returns a stream of normally distributed random numbers.
  46.  
  47. > box_muller :: [num] -> [num]
  48. > box_muller (x1:x2:xs) = x1*m:x2*m:rest, if r <= 1
  49. >                = rest, otherwise
  50. >              where r = x1^2 + x2^2
  51. >                    m = sqrt(-2*log r/r)
  52. >                    rest = box_muller xs
  53.