Mike
Mike

Reputation: 390

Generate random between [0, 1)

I want to generate a random float value between 0 and 1 excluding 1, I.e. [0, 1). I've searched a lot but I couldn't find an answer of this. I've tried the following trick however it generates a negative values

(double)rand()/(double)RAND_MAX-1;

Upvotes: 0

Views: 1139

Answers (2)

Michał Walenciak
Michał Walenciak

Reputation: 4369

You just need to divide by RAND_MAX including +1. Like this:

(double)rand()/((double)RAND_MAX+1);

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96258

You need parentheses to force the right order:

(double)rand()/((double)RAND_MAX + 1);

Also note, that you need +1, not -1.

Upvotes: 2

Related Questions