Thursday, 28 June 2012

Pick a number, any number

I have been learning C lately, just for the craic, and was trying to write a small program on the RPi to roll a dice - still not programming the next space shuttle - which to my mind should be very easy since there is a random number function in C - the output of a number of iterations was a little too predictable though:


2, 5, 4, 2, 6, 2, 5, 1, 4, 2
Even though I have been learning to program for quite a while, I have never used a random number generator for anything.  It comes as a surprise when computers aren't behaving as I expect - this is one of the limitations of being self-taught, that you don't get some of the very basics about how computers behave.  This type of thing is probably covered in Programming in C 101, but had me thinking I should play the numbers in the Lottery this weekend!
Why is a random number function so predictable??
Because the rand() function is seeded with the same number everytime - so the function is pseudo-random really.  A truly random number generator will use some non-constant value as a seed, typically system time.





No comments:

Post a Comment