# Getting a random float value

Discussion in 'Mac Programming' started by SqueegyX, Mar 29, 2008.

1. ### SqueegyX macrumors regular

Joined:
Mar 24, 2008
#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.

2. ### CaptainZap macrumors regular

Joined:
Jan 17, 2007
#2
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;`

3. ### SqueegyX thread starter macrumors regular

Joined:
Mar 24, 2008
#3
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.

4. ### kpua macrumors 6502

Joined:
Jul 25, 2006
#4
That's C for ya.

5. ### sord macrumors 6502

Joined:
Jun 16, 2004
#5
Your while doesn't work because its going to loop until x is 0, which will of course result in x being 0...

6. ### CaptainZap macrumors regular

Joined:
Jan 17, 2007
#6
Wow, lmao, that was supposed to be a 1. Wow wow wow wow wow