I'm trying to create a random float between 0.15 and 0.3 in Objective-C. The following code always returns 1:
int randn = (random() % 15)+15;
float pscale = (float)randn / 100;
What am I doing wrong?
I'm trying to create a random float between 0.15 and 0.3 in Objective-C. The following code always returns 1:
int randn = (random() % 15)+15;
float pscale = (float)randn / 100;
What am I doing wrong?
try
Using srandom() and rand() is unsafe when you need true randomizing with some float salt.
On MAC_10_7, IPHONE_4_3 and higher you can use arc4random_uniform(upper_bound)*. It allows to generate true random integer from zero to *upper_bound*.
So you can try the following
To add to @Caladain's answer, if you want the solution to be as easy to use as
rand()
, you can define these:Feel free to replace
CGFloat
withdouble
if you don't have access to CoreGraphics.I ended up generating to integers one for the actual integer and then an integer for the decimal. Then I join them in a string then I parse it to a floatvalue with the "floatValue" function... I couldn't find a better way and this works for my intentions, hope it helps :)
Easiest.
Your code works for me, it produces a random number between 0.15 and 0.3 (provided I seed with
srandom()
). Have you calledsrandom()
before the first call torandom()
? You will need to providesrandom()
with some entropic value (a lot of people just usesrandom(time(NULL))
).For more serious random number generation, have a look into
arc4random
, which is used for cryptographic purposes. This random number function also returns an integer type, so you will still need to cast the result to a floating point type.