Talk About Network

Google





Programming > C - C++ Learning > Re: generate ra...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 4 of 4 Topic 4128 of 4400
Post > Topic >>

Re: generate random double between 0 and 1

by "Jim Langston" <tazmaster@[EMAIL PROTECTED] > Apr 28, 2008 at 10:24 AM

carvalho.miguel@[EMAIL PROTECTED]
 wrote:
> On 27 Abr, 21:37, Krzysztof Mitko <kmi...@[EMAIL PROTECTED]
> wrote:
>> carvalho.mig...@[EMAIL PROTECTED]
 twierdzi, że:
>>
>>> im trying to generate a double precision random number between 0 and
>>> 1, but i keep getting 0 only.
>>> static double randomDouble()
>>> {
>>> return static_cast<double>(rand() / RAND_MAX);
>>> }
>>
>> RAND_MAX is an integer
>>
>> rand() returns an integer
>>
>> (rand() / RAND_MAX) is a division of integer by integer, suprisingly
>> giving the integer :). Further cast doesn't matter, since you can
>> only get 0 or 1 (if rand() results in RAND_MAX value).
>> One of them should be a double. My manual says that the proper
>> formula is:
>>
>> return rand() / (RAND_MAX + 1.0);
>>
>> --
>> If an experiment works, something has gone wrong.
>
> nice, it worked. and you're right i was dividing 2 integers getting a
> new integer, really nubish of me.
> thanks for the help and explanation =)

Alternative is:

return static_cast<doube>( rand() ) / RAND_MAX;

This casts the return from rand() to a double, then devides by RAND_MAX. 
Since at this pont rand() is a double, you will get floating point 
divisiion.



-- 
Jim Langston
tazmaster@[EMAIL PROTECTED]

 




 4 Posts in Topic:
generate random double between 0 and 1
carvalho.miguel@[EMAIL PR  2008-04-27 13:15:36 
Re: generate random double between 0 and 1
Krzysztof Mitko <kmitk  2008-04-27 20:37:09 
Re: generate random double between 0 and 1
carvalho.miguel@[EMAIL PR  2008-04-27 13:40:41 
Re: generate random double between 0 and 1
"Jim Langston"   2008-04-28 10:24:19 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
localhost-V2008-12-19 Wed Jan 7 14:07:11 PST 2009.