PDA

View Full Version : Getting a random float value




SqueegyX
Mar 29, 2008, 05:45 PM
This seems like a totally stupid question that I can't find the answer to. How to I get a random float?

I have found random() is not a number at all, but some random set of binary bits, is that right?

This gives an integer it seems, ranged 1 -100.
random() % 100

But how do I get a random float, ranged 0-1? In most other languages I have used a call to rand() will simply return just that. It is then up to you to make an integer or make that value fit your desired range.

I'm sure this is a silly question, but my Objective-C noobness, and Google, are failing me.



CaptainZap
Mar 29, 2008, 06:02 PM
Try something like this, where x is a float

x = random();
while (x > 0)
x /= 10.0;


Edit: Don't worry. My noobness failed too. That doesn't work.

Edit2: K, for some reason the while statement didn't work but this statement does
float x = (float) (random() % 1000000) / 1000000;

SqueegyX
Mar 29, 2008, 06:36 PM
OK, I got it. Apparently there is a RAND_MAX constant that is the maximum value of the random() function. So:

(float)random()/RAND_MAX

Pretty verbose for something other languages give you for free, but it works.

kpua
Mar 29, 2008, 10:17 PM
Pretty verbose for something other languages give you for free, but it works.

That's C for ya.

sord
Mar 30, 2008, 12:13 AM
Try something like this, where x is a float

x = random();
while (x > 0)
x /= 10.0;


Edit: Don't worry. My noobness failed too. That doesn't work.

Edit2: K, for some reason the while statement didn't work but this statement does
float x = (float) (random() % 1000000) / 1000000;
Your while doesn't work because its going to loop until x is 0, which will of course result in x being 0...

CaptainZap
Mar 30, 2008, 10:27 AM
Your while doesn't work because its going to loop until x is 0, which will of course result in x being 0...

Wow, lmao, that was supposed to be a 1. Wow wow wow wow wow