3

Possible Duplicates:
Generating Random Numbers in Objective-C
What's the most optimal way to get a random floatingpoint number between floatA and floatB?

Hi,

I want to generate a random float number like

float scale = randFloat(0.5f, 2.0f);

How do I do this in objective-c?

Shaunak
  • 17,377
  • 5
  • 53
  • 84
DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601

2 Answers2

4

Here is how you generate them :

// Get random value between 0 and 99
int x = arc4random() % 100;

// Get random number between 500 and 1000
int y =  (arc4random() % 501) + 500);

You can easily extend this for any range you need.

Hope that helps.

Shaunak
  • 17,377
  • 5
  • 53
  • 84
1

Generate two random integers and divide one by the other. With some manipulation you can introduce a range.

Also, depending on the required resolution you could simply generate a single random integer and divide it by a fixed integer to get your float. For example, generate a random number between 0 and 100,000 and divide it by 100,000. You can offset and shift the result around to get the range you need.

martin's
  • 3,853
  • 6
  • 32
  • 58