random number

Hello,

Have trouble generating single number between 0 and 1 with variable precision. In some cases I need a number with 4 decimal places and another time with 20. Should be a function like: returnRandomNumber(start, end, decimal points)

-Max
Generating the random number is easy:

variable randomNUmber = abs(enoise(1))


I'm a bit mystified as to why you want the digits tho'. If you just want to print out the number to the history line you could use:

printf "%1.4f\r", abs(enoise(1))
How about:

 
Function returnRandomNumber(decimalpoints)
    variable decimalpoints
    return round((enoise(0.5)+0.5)*10^decimalpoints)/10^decimalpoints
End

Function MCtest(decimalpoints,n)
    variable decimalpoints,n
    variable i
    make /o/n=(n) w
    for (i=0; i<n; i+=1)
        w[i] = returnRandomNumber(decimalpoints)
    endfor
    Make/N=10/O w_Hist;DelayUpdate
    Histogram/B={0,0.1,10} w,w_Hist;DelayUpdate
End


John Bechhoefer
Department of Physics
Simon Fraser University
Burnaby, BC, Canada
THats probably ok, but I can never remember how small a number a single precision wave can hold. SHould probably make it double precision.

ANother way could be to produce a random number using enoise. Then do a sprintf operation to put it into a string, truncated to the right numbe of digits. Then use str2num to get the number back again. However, the sprintf rounds the last digit so the other way is probably better.
Thanks. Also, just realized there is a small bug. One should use floor, not round, to prevent the end bins from being underrepresented. Thus:

Function returnRandomNumber(decimalpoints)
    variable decimalpoints
    return floor((enoise(0.5)+0.5)*10^decimalpoints)/10^decimalpoints
End
 
Function MCtest(decimalpoints,n)
    variable decimalpoints,n
    variable i
    make /o/d/n=(n) w
    for (i=0; i<n; i+=1)
        w[i] = returnRandomNumber(decimalpoints)
    endfor
    Make/N=10/O w_Hist;DelayUpdate
    Histogram/B={0,0.1,10} w,w_Hist;DelayUpdate
End


This can be tested with

MCtest(1,1e4)


Notice that all bins have 1e4*0.1 = 1000 ± sqrt(1000) counts and that repeated execution shows that fluctuations in all bins are symmetric about 1000 (the poor man's way of doing statistics....).


John Bechhoefer
Department of Physics
Simon Fraser University
Burnaby, BC, Canada