📜 ⬆️ ⬇️

Interesting RANDOM behavior in zsh

After reading about the Paraty Monty Hall , I decided to write a script that simulates this experiment several thousand times (before I saw these implementations ).
While testing pieces of code, I came across an interesting RANDOM behavior in the shell of my linux.
As you know, RANDOM is a variable that takes a pseudo-random value from 0 to 32k.
How many times out of 10,000 - will RANDOM be odd?
well, about 5,000 times ... Check?
% for i in {1..10000} ; do test $(( RANDOM % 2 )) -eq 1 && echo 1 ; done | wc -l
4985

And if I execute this command again, will I get 4985 again? It seems not to.
However, it all depends on the shell in which we work.


in bash, everything looks as expected:
$ for i in {1..10000} ; do test $(( RANDOM % 2 )) -eq 1 && echo 1 ; done | wc -l
5057
$ for i in {1..10000} ; do test $(( RANDOM % 2 )) -eq 1 && echo 1 ; done | wc -l
4940
$ for i in {1..10000} ; do test $(( RANDOM % 2 )) -eq 1 && echo 1 ; done | wc -l
5021


However, in zsh, within a session - RANDOM is not that identical, but in some cases it is quite predictable.

% for i in {1..10000} ; do test $(( RANDOM % 2 )) -eq 1 && echo 1 ; done | wc -l
4985
% for i in {1..10000} ; do test $(( RANDOM % 2 )) -eq 1 && echo 1 ; done | wc -l
4985
% for i in {1..10000} ; do test $(( RANDOM % 2 )) -eq 1 && echo 1 ; done | wc -l
4985


Here is such a “bagofich”.
Two sets of commands, distinguished by the fact that one of them uses standard streams, and the other intermediate file
 for i in {1..10000};  
   do echo $ ((RANDOM% 2)); 
 done |  awk '/ 1 / {N ++} END {print N}' 

 for i in {1..10000};  
   do echo $ ((RANDOM% 2)); 
 done> tmp_file && awk '/ 1 / {N ++} END {print N}' tmp_file
It does the same thing - it considers the number of odd fallouts of RANDOM. By running the first of the same zsh session, we will get the same result, and the second will return a new one each time.

')

Source: https://habr.com/ru/post/101722/


All Articles