Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Random numbers in functions



Justin M Wozniak wrote:
> Hello
>  	I'm trying to obtain random numbers from my own distribution and 
> I'd like to wrap all the arithmetic in ZSH functions which query $RANDOM 
> or rand48().  However, I keep getting the same numbers over and over 
> again.

rand48() is written specifically to be able avoid this; see also
the documentation for zsh/mathfunc.

  zmodload -i zsh/mathfunc

  local param1 param2

  print $(( rand48(param1) ))
  print $(( rand48(param1) ))
  print

  param2=$param1

  print $(( rand48(param1) ))
  print $(( rand48(param1) ))
  print

  print $(( rand48(param2) ))
  print $(( rand48(param2) ))

gives

  0.16013394447730178
  0.84537721340609906

  0.65599208737134518
  0.3807377705316064

  0.65599208737134518
  0.3807377705316064

Note the values of the second and third pairs are the same because they
used the same seed stored in the parameter.  The values in the parameter
are plain text (six bytes as an ASCII hex string).  So the thing to do
is to save the value of the parameter in a file and restore it when you
want to continue from where you left off.

  zmodload -i zsh/mathfunc

  local param

  if [[ -f ~/.zsh_rand48 ]]; then
     param="$(<~/.zsh_rand48)"
  fi

  print $(( rand48(param) ))

  print $param >~/.zsh_rand48

rand48() should give much better random numbers than $RANDOM anyway.

-- 
Peter Stephenson <pws@xxxxxxx>                  Software Engineer
CSR PLC, Churchill House, Cambridge Business Park, Cowley Road
Cambridge, CB4 0WZ, UK                          Tel: +44 (0)1223 692070



Messages sorted by: Reverse Date, Date, Thread, Author