Kai-Uwe Bux
12/6/2008 10:09:00 AM
Rolf Magnus wrote:
> Pete Becker wrote:
>
>> On 2008-12-05 17:19:37 -0500, sintral <sintral@gmail.com> said:
>>
>>> I'm sure this is simple, I've tried to find it in the group, but no
>>> luck.
>>>
>>> I'm generating one random float between 0 and 1: x = (float) rand()/
>>> RAND_MAX;
>>> How to I generate a second random number between 0 and my 1st random
>>> number; 1 - x?
>>>
>>> I saw between because the sum of x and y must be < 1; (non-inclusive).
>>
>> Generate a number between 0 and 1, and multiply it by (1-x).
>>
>> But there are some boundary conditions that you have to watch for. In
>> particular, (float)rand()/RAND_MAX can be 1, and in that case you can't
>> generate a non-negative value that you can add to x to give you a value
>> that's < 1. You really need to divide by (RAND_MAX + 1), to generate a
>> value that's in the range 0 <= x < 1. But you have to be careful there,
>> because if RAND_MAX is equal to UINT_MAX, adding 1 to it will give you
>> 0. None of this is really hard, but you have to be a little careful.
>> Details are left as an exercise.
>
> Another thing is that on most platforms, float cannot store the exacxt
> value of RAND_MAX. double would be a better choice.
True, but the story is a little more complicated. You would want RAND_MAX+1
anyway; that usually is a power of 2 and can be represented exactly by a
float. Now, it is implementation defined whether converting RAND_MAX to a
float will yield the power of 2 or the largest representable number below.
However, even if converting to float will do the RightThing(tm), you run
into trouble since some random values will also be converted to the same
float. In that case, the quotient is 1 and not <1.
Best
Kai-Uwe Bux