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

Re: rigorously predictable random numbers



On Thu, May 2, 2024, at 9:23 PM, Ray Andrews wrote:
> ... the result of the first $RANDOM is always exactly the result of the 
> second $RANDOM in the previous call to the script.

As zshparam(1) says:

	The values of RANDOM form an intentionally-repeatable
	pseudo-random sequence; subshells that reference RANDOM
	will result in identical pseudo-random values unless the
	value of RANDOM is referenced or seeded in the parent shell
	in between subshell invocations.

Referencing RANDOM advances the sequence, but doing so in $(...)
-- or any other subshell -- causes that progress to be discarded
upon returning to the parent shell, and the next reference to
RANDOM will "rewind" to the first value seen in that subshell.

	% typeset -p RANDOM
	typeset -i10 RANDOM=9493
	% (repeat 3; do typeset -p RANDOM; done)
	typeset -i10 RANDOM=5570
	typeset -i10 RANDOM=30244
	typeset -i10 RANDOM=21515
	% typeset -p RANDOM
	typeset -i10 RANDOM=5570


> This might not be 
> as unexpected in a function where at least it's the same shell, but a 
> script, seems to me, should always have a virginal notion of $RANDOM, 
> no?  Yet it remembers the previous result from another shell.

There are no other shells, other than the $(...) subshells.  You
are using the "." command, which sources the given script in the
current shell.


> I have 
> the vaguest fragment of memory that we discussed this on the list once 
> before.

https://www.zsh.org/mla/workers/2015/msg00549.html
https://www.zsh.org/mla/workers/2017/msg00586.html
https://www.zsh.org/mla/users/2017/msg00618.html
https://www.zsh.org/mla/workers/2019/msg00887.html
https://www.zsh.org/mla/workers/2023/msg00012.html
https://www.zsh.org/mla/workers/2023/msg00208.html
https://www.zsh.org/mla/users/2023/msg00475.html


-- 
vq




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