On 27/05/2011, at 1:16 PM, Conrad Shultz wrote:

> I'm pretty sure your problem has to do with overflowing your data types.
> "unsigned" is getting treated as "unsigned int", which will be too
> small to hold the value after you, for some reason I'm not clear on,
> multiply by 10000.
> 
> When I wrote some sample code that used NSUInteger instead, everything
> worked properly.  When I compiled using 32-bit settings (instead of
> native), the time interval produced using your code was wrong (and
> constant, explaining your problem).
> 
> This makes sense: in 32 bit, NSUInteger is typedef'd to unsigned int, in
> 64 it is unsigned long, which _can_ accommodate .


This makes complete sense. However, it seems not to be the case. I found out 
why I'm getting the same random numbers each time - explain in a sec.

But this code does *appear* to give random results (having fixed the format 
specifier issue):

        unsigned seed = (unsigned)([NSDate timeIntervalSinceReferenceDate] * 
10000.0);
        
        NSLog(@"seed: %u", seed );
        
        srandom( seed );
        
        long r = random();
        
        NSLog(@"random: %ld", r );


I should mention this is in a 64-bit build, so doesn't that mean that 
'unsigned' is 64 bits? However, the problem with a 32-bit build is definitely 
an issue, so I'll revise the code anyway.

The x10000 is an attempt (probably misguided) to ensure a truly varying seed 
since casting to an int would only give a value that changed every second 
because NSTimeInterval is a floating point value in seconds. That is in fact 
entirely sufficient - you can't launch the app more than once a second!

The *real* reason I was getting the same sequence from random() is that this is 
a document-based app (actually a simple game, random is used to set up a 
variable initial game state) and the first document is created before 
-applicationDidFinishLaunching: is invoked. Creating the document loads the nib 
and initialises the data structures for the game, including the 'random' 
initial state. This order of initialisation during launch is something I've run 
into before, but had forgotten about - I was assuming that the app launched, 
then it opened the first document.

Moving the seeding to -applicationWillFinishLaunching: instead solved the 
problem since this is definitely called prior to creating the first document.

Thanks to everyone for helping straighten this out - 32/64 bit issues are still 
rather new to me.

--Graham


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to