Little to be noted. An algorithm starting at X > 0 and at each step takes a random number from (0,X) and replaces X , and this is not good. What for? Since (provided that random behaves correctly), the expected value at each step is in the middle of the interval (0,X) . This means that the sequence of these numbers will converge to 0 up to (1/2)^N Indeed, it is easy to see that most numbers are close to 0 even for enormous value. This means that the distribution of these numbers is not uniform, which is the desired property most of the time.
This is the main drawback, although the complexity of generating the N number of O(N) and (more importantly) the use of memory is O(1) .
Another solution is to simply take the random numbers N and sort them. This is not bad, although the complexity of this algorithm is O(N log(N)) (or rather, the same as the complexity of the basic sorting algorithm), which can be reduced to O(N) if we put the elements in order instead of sorting, but memory usage is O(N) - we must remember all the elements. However, these numbers will be evenly distributed, which is a big advantage!
Following the idea in the article " Generating Sorted Lists of Random Numbers " by John Louis Bentley, here is an algorithm that is probably the most optimal one (at least that I know) and produces uniformly distributed numbers:
import math import random def generate( min = 0, max = 10, number = 100 ): start = 0 for i in xrange( number, 0, -1 ): start = start + math.log( random.random( ) ) / i next = math.exp( start ) * ( max - min ) + min yield next for number in generate( ): print number
Note that the complexity of this algorithm is still O(N) (which, I doubt, may be lower), but the memory usage is O(1) , and these numbers are evenly distributed in the interval (min,max) , which is not so obvious but true. The only drawback is that we need to know how many numbers we want to create before running.
Also look at this topic:
Generating sorted random numbers without sorting? O (n)
May be helpful.