Skip site navigation (1)Skip section navigation (2)
Date:      Sat, 21 May 2016 14:55:17 -0700
From:      Conrad Meyer <cem@FreeBSD.org>
To:        Pedro Giffuni <pfg@freebsd.org>
Cc:        src-committers@freebsd.org, svn-src-all@freebsd.org,  svn-src-head@freebsd.org
Subject:   Re: svn commit: r300377 - head/sys/compat/ndis
Message-ID:  <CAG6CVpV_3%2B%2BWqg2X23=RM942zaDkyL6fxH2YN0TXUqpPjneCOw@mail.gmail.com>
In-Reply-To: <a88c14ea-ee78-54de-6142-08a561a49d98@FreeBSD.org>
References:  <201605211752.u4LHqiHQ031457@repo.freebsd.org> <CAG6CVpXjU3tHdar7d=xyr%2BTmffg0NrQu3q7SD=b6%2BjF=yvVr-Q@mail.gmail.com> <a88c14ea-ee78-54de-6142-08a561a49d98@FreeBSD.org>

next in thread | previous in thread | raw e-mail | index | archive | help
On Sat, May 21, 2016 at 1:40 PM, Pedro Giffuni <pfg@freebsd.org> wrote:
>
>
> On 05/21/16 14:05, Conrad Meyer wrote:
>> Won't this still return a negative integer in many cases?
>>
>> random(9) returns u_long, whereas this rand() routine returns 'int'.
>>
>> Even on architectures where long is the same size as ordinary
>> integers, the range of possible results of the 'random() / 2 + 1'
>> expression, before implicit cast to signed, is [1, 2^31] (inclusive).
>
>
> According to:
> sys/libkern/random.c
>
> The result is uniform on [0, 2^31 - 1].

Ah, I missed that.  Sorry!  In that case, I'm not sure why this is
needed =E2=80=94 the result fits in a non-negative 2's complement signed
integer.

>> 2^31 is not representable by typical signed 32-bit integers, so this
>> will wrap to INT_MIN.  Also, I'm not sure why zero is excluded from
>> the range.
>>
>
> It is not a good reason but the zero is sometimes inconvenient: if
> the value is going to be used as a multiplier in some calculation
> it will basically kill the random component.

Sure, but anyone using a random number as a multiplier must consider
the range of the random function.  They should handle rand() =3D=3D 0
(perhaps by this '/ 2 + 1' construct).  I don't think that is the
responsibility of a rand() function.

Best,
Conrad



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?CAG6CVpV_3%2B%2BWqg2X23=RM942zaDkyL6fxH2YN0TXUqpPjneCOw>