Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Random Numbers Between Two Numbers in Objective-C

I have two text boxes and user can input 2 positive integers (Using Objective-C). The goal is to return a random value between the two numbers.

I've used "man arc4random" and still can't quite wrap my head around it. I've came up with some code but it's buggy.

float lowerBound = lowerBoundNumber.text.floatValue; float upperBound = upperBoundNumber.text.floatValue; float rndValue; //if lower bound is lowerbound < higherbound else switch the two around before randomizing. if(lowerBound < upperBound) {     rndValue = (((float)arc4random()/0x100000000)*((upperBound-lowerBound)+lowerBound)); } else  {     rndValue = (((float)arc4random()/0x100000000)*((lowerBound-upperBound)+upperBound)); } 

Right now if I put in the values 0 and 3 it seems to work just fine. However if I use the numbers 10 and 15 I can still get values as low as 1.0000000 or 2.000000 for "rndValue".

Do I need to elaborate my algorithm or do I need to change the way I use arc4random?

like image 778
Demasterpl Avatar asked Mar 13 '12 04:03

Demasterpl


People also ask

How do you generate a random number in Objective C?

How Do I Generate a Random Number in Objective-C? tl;dr: Use arc4random() and its related functions. Specifically, to generate a random number between 0 and N - 1 , use arc4random_uniform() , which avoids modulo bias.

What is arc4random_uniform?

arc4random_uniform(_:) returns a random number between zero and the first parameter, minus one. drand48() returns a random Double between 0.0 and 1.0.


1 Answers

You could simply use integer values like this:

int lowerBound = ... int upperBound = ... int rndValue = lowerBound + arc4random() % (upperBound - lowerBound); 

Or if you mean you want to include float number between lowerBound and upperBound? If so please refer to this question: https://stackoverflow.com/a/4579457/1265516

like image 95
eveningsun Avatar answered Sep 21 '22 09:09

eveningsun