Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random float between 0 and 1

I'm trying to generate a random number that's between 0 and 1. I keep reading about arc4random(), but there isn't any information about getting a float from it. How do I do this?

like image 474
jini Avatar asked Mar 02 '11 19:03

jini


People also ask

How do you create a random float between 0 and 1?

Generate a random float number between 0 to 1Use a random. random() function of a random module to generate a random float number uniformly in the semi-open range [0.0, 1.0) . Note: A random() function can only provide float numbers between 0.1. to 1.0.

Does random random () include 0 and 1?

The Random random() method generates the number between 0.0 and 1.0.


1 Answers

Random value in [0, 1[ (including 0, excluding 1):

double val = ((double)arc4random() / UINT32_MAX); 

A bit more details here.

Actual range is [0, 0.999999999767169356], as upper bound is (double)0xFFFFFFFF / 0x100000000.

like image 53
Vladimir Avatar answered Sep 22 '22 02:09

Vladimir