Posted: 13th Apr 2004 23:17
I looked around on the codebase and I couldn't find anything that would give me normally distrubuted random numbers (a bell curve) so I wrote these functions. Credit to Kevil for the log function.

To get the normal distribution I applied the Box-Muller transformation to the regular rnd function.

There are a few functions included to make this work, but the main two are:

randnormal takes two parameters. The first is the mean and the second is the standard deviation.

randrange takes three paremeters. The first two are the lower and upper limit of the range and the third value is either the standard deviation or a value of zero which will the give the default standard deviation of a forth of the range.

+ Code Snippet
#constant PI 3.1415926535898
randomize timer()


function randrange(low#,high#,std#)
   mean#=(high#-low#)/2.0+low#
   if std#=0
      std#=(high#-low#)/4.0
   endif
   repeat
      x#=randnormal(mean#,std#)
   until (x#>low#) and (x#<high#)
endfunction x#

function randnormal(mean#,std#)
   x#=gennor()*std#+mean#-std#
endfunction x#

function surand()
   x#=rnd(32768)/32768.0
endfunction x#

function urand(low#, high#)
   x#=low#+(high#-low#)*surand()
endfunction x#


function gennor()
   x1#=surand()
   x2#=surand()
   y# = sqrt( - 2.0*ln(x1#) )* cos( 2.0* PI* x2# )
   if rnd(1)=0
      y#=2.0-y#
   endif
endfunction y#

function log(base#,answer#)
   log#=sqrt(answer#/base#)
   repeat
      log#=log#-(((base#^log#)-answer#)/(base#^log#*ln(base#)))
   until abs((base#^log#)-answer#)<=0.0001
endfunction log#


function ln(answer#)
   e#=2.718281828459045
   ln#=sqrt(answer#/e#)
   repeat
      ln#=ln#-(((e#^ln#)-answer#)/(e#^ln#))
   until abs((e#^ln#)-answer#)<=0.0001
endfunction ln#


function nearint(f#)
   i=int(f#)
   t#=f#-i
   if t#>0.5 then inc i
endfunction i