Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

SqueegyX

macrumors regular
Original poster
Mar 24, 2008
108
1
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.
Code:
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

macrumors regular
Jan 17, 2007
170
0
Try something like this, where x is a float

Code:
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
Code:
float x = (float) (random() % 1000000) / 1000000;
 

SqueegyX

macrumors regular
Original poster
Mar 24, 2008
108
1
OK, I got it. Apparently there is a RAND_MAX constant that is the maximum value of the random() function. So:

Code:
(float)random()/RAND_MAX

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

sord

macrumors 6502
Jun 16, 2004
352
0
Try something like this, where x is a float

Code:
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
Code:
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...
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.