Getting a random float value

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

  1. SqueegyX macrumors regular

    Mar 24, 2008
    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.
  2. CaptainZap macrumors regular

    Jan 17, 2007
    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;
  3. SqueegyX thread starter macrumors regular

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

    Pretty verbose for something other languages give you for free, but it works.
  4. kpua macrumors 6502

    Jul 25, 2006
    That's C for ya.
  5. sord macrumors 6502

    Jun 16, 2004
    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

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

Share This Page