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

Re: random numbers



Sure.  More generally, you can get a pseudo-random integer from 0 to N-1 by rerolling whenever you get anything > N*floor(32767/N). My point was that even if you don't do that, the actual variation from uniformity is not huge as long as you keep your divisor in a reasonable range relative to 32767.

On Mon, Sep 15, 2025 at 3:12 PM Roman Perepelitsa <roman.perepelitsa@xxxxxxxxx> wrote:
You can get a uniform random number from [0, 10) like this:

    integer n
    while true; do
      (( n = RANDOM ))
      if (( n <= 32760 )); then
        (( n %= 10 ))
        break
      fi
    done

Roman

On Mon, Sep 15, 2025 at 8:56 PM Mark J. Reed <markjreed@xxxxxxxxx> wrote:
I think i know why, it's because zsh's RANDOM tops out at 32,767, but this insures that the first digit of a string of random numbers isn't random but strongly weighted to 1 and 2, with 3 also weighted.

I mean, only if you use the whole value of RANDOM directly, which most applications of random numbers don't do. If you do the usual trick of taking the remainder of RANDOM modulo a range, e.g. picking random digits one at a time with (( RANDOM % 10 )), you won't see such a strong weighting. In the case of single digits you are 0.03% less likely to get an 8 or 9 than a 0 through 7, but that's a pretty mild deviation from uniformity.

On Mon, Sep 15, 2025 at 9:36 AM Clinton Bunch <cdb_zsh@xxxxxxxxxxx> wrote:

I think i know why, it's because zsh's RANDOM tops out at 32,767, but this insures that the first digit of a string of random numbers isn't random but strongly weighted to 1 and 2, with 3 also weighted.  Is this worth worrying about?  I'd say so.  Perhaps it should max out at 10,000 or 100,000 or even offer a user selectable range?  Or do we have other tricks for coping with this?  I find zsh to be quite competent mathematically so having to use an external utility to get really random numbers seems not up to snuff.

Check out the zsh/random module in the current test release and the zrand_int math function.



--
Mark J. Reed <markjreed@xxxxxxxxx>


--
Mark J. Reed <markjreed@xxxxxxxxx>


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