On Sat, May 21, 2016 at 1:40 PM, Pedro Giffuni <p...@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 — 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() == 0
(perhaps by this '/ 2 + 1' construct).  I don't think that is the
responsibility of a rand() function.

Best,
Conrad
_______________________________________________
svn-src-all@freebsd.org mailing list
https://lists.freebsd.org/mailman/listinfo/svn-src-all
To unsubscribe, send any mail to "svn-src-all-unsubscr...@freebsd.org"

Reply via email to