0

Possible Duplicate:
Correcting floating point numbers

float randNum = arc4random()%(100)-1;

I read somewhere that this will give me random numbers between 1-100. Or something close to that.

This line seems to work all the time, but I convert this number to an NSString for storage/printing to text, and then convert it back to a float for ordering and other calculations. But when I get that float back sometimes it looks something like gibberish; like this in the variable view:

9   float   9.75303731e-41   

Why would converting to an NSString and back to a float ruin the float value I'm using? (e.g. What could I have screwed up? Or should I be using CGFloat instead?)

I think this is all the pertinent code:

NSMutableArray *stringArray = [[NSMutableArray alloc] init];
floatArray[30];
// put three random floats into an NSMutableArray of NSStrings
for(int i = 0; i < 3; i++)
{
    float randNum = arc4random()%(100)-1;
    NSString *randString = [NSString stringWithFormat:@"%.3f", randNum];
    [stringArray addObject:randString];
}

// convert NSStrings back to float
for(NSString *string in stringArray)
{
    float temp = [string floatValue];
    floatArray[iterator] = temp;
}

Thanks in advance for any help/advice.

EDIT: When I step through the code it looks like the float value looks sane until the line "float temp = [string floatValue]", which is where the value seems to be garbaged.

Community
  • 1
  • 1
user990769
  • 115
  • 2
  • 12
  • Instead of converting to NSString, why dont you convert to NSNumber and save it in array and then get it back from NSNumber object? – iDev Nov 20 '12 at 17:56
  • ACB - Thanks for the suggestion. I will try that out. Inafziger - Thanks for posting the possible duplicate. I will try out ACB's suggestion. – user990769 Nov 20 '12 at 17:59
  • 2
    Why are you subtracting 1? `arc4random()%(100)` returns a number from 0-99, so you should _add_ 1 to shift up to 1-100. – Barmar Nov 20 '12 at 18:04
  • Again, code I had found online. – user990769 Nov 20 '12 at 18:40

1 Answers1

1

Why are you using float when the result from arc4random() is a uint32_t? Switching to integer types would almost certainly get around all this, as I suspect the problem is because of the conversion to string form allowing only 3 significant digits. What happens if you use %.15f as your format?

Sidenote: use arc4random_uniform() - it's simpler and guaranteed to be a uniformly random distribution within that range.

Wade Tregaskis
  • 1,996
  • 11
  • 15