Re: random numbers
Roman Perepelitsa <[email protected]>
| Newsgroups | gmane.comp.shells.zsh.devel,gmane.comp.shells.zsh.user |
|---|---|
| Message-ID | <CAN=4vMq8yyS3TbdvrePB2h=A38qRAqyOgc9BFeRqJ6VEOjKvQg@mail.gmail.com> |
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 <[email protected]> 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 <[email protected]> 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 <[email protected]>
>