Saturday, March 7, 2015

Post #6 - Random numbers

I usually end up being behind a post if I have homework or other life stuff going on that needs to get done, so here's a program that was going to be posted yesterday.


Using the libraries cstdlib for the srand() and rand() functions, and ctime for the time() function, the program displays a random year within the range 1985 - 2015. The range limit is achieved by setting the random year to display equal to the remainder of the randomly generated number divided by 31, resulting in an integer between 0 and 30 (the computer counts starting from 0, not starting from 1, so in our counting style 0-30 would be 1-31). 

We want the difference of the years (2015 - 1985 = 30) plus the starting year (1985) to be the range of the random year, but if 30 was used as the divisor, the range would be one year off from 2015 (since in computer numbers, (0 + 29) = 1-30, it would count from (0 + 1985) to (29 + 1985) which is 1985 - 2014). The off-by-one error can be fixed, because another 1 was not added to 30 to account for 2015 as one of the years, just change 30 to 31, thus raising the range to 1-31 and including 2015 in the computer's random years selection.

This sounds confusing but try reading the 0 of the modulus (%) results as a 1, and adding 1 to every integer in the range including the last number. This kinda converts it to human-range starting with 1, and to convert back, subtract 1 from every number for counting from 0.

Here's the output:
This program randomly chooses a year between 1985 and 2015.

The random year is 1985

This program randomly chooses a year between 1985 and 2015.
The random year is 2000

This program randomly chooses a year between 1985 and 2015.
The random year is 2015
After re-running this one for a while, 2015 finally appeared (1/30% chance...) (thought something was wrong with my logic for a sec. turns out it just needed more chances to occur).

The off-by-one is easy to miss, so when in doubt, know that the computer almost always  starts counting from 0 and a simple overlooked thing like adding 1 can cause the range to fall into place correctly.

No comments:

Post a Comment