In: Statistics and Probability
The first random number generator comes from Python itself.
To use it you need to import the Python package. Then call the random() method. See below.
import random
print (random.random())
It is important to know that a random number generator really is random. If so, it should have uniform distribution between 0 and 1. Test the random number generators in Python for uniformity.
What you are asking for is not random; indeed, it is fairly structured. The point of random data is that it isn't structured: you can't say anything about what the values will be, only what they will be on average.
You can still do what you want, though: just specify the ranges you want your numbers to fall into.
>>> def random_function(*args): ... n = sum(args) ... bottom = 0 ... for m in args: ... for _ in range(m): ... yield random.uniform(bottom, bottom + m/n) ... bottom += m/n ... >>> list(random_function(6,3,1)) [0.1849778317803791, 0.2779140519434712, 0.08380168147928498, 0.5477412922676888 , 0.5158697440011519, 0.5535466918038039, 0.8046993690361345, 0.714614514522802, 0.7102988180048052, 0.9608096335125095] >>> list(random_function(6,3,1)) [0.29313403848522546, 0.5543469551407342, 0.14208842652528347, 0.344464024804118 7, 0.3168266508239002, 0.5956620829410604, 0.673021479097414, 0.7141779120687652 , 0.7783099010964684, 0.9103924993423906]
Explanation:
Given (6,3,1), work out their sum (10). We want six numbers between 0 and 6/10, three numbers between 6/10 and 6/10 + 3/10, and one number between 6/10 + 3/10 and 6/10 + 3/10 + 1/10. We can generate these by calling
random.uniform(0, 6/10) six times, random.uniform(6/10, 9/10) three times, and random.uniform(9/10, 1) once.
Another approach could be
As part of the random module (import random), you can use random.uniform(a,b) instead of random.random() where a to b is the range in floating point.
But second approach may or may not have significant effect on uniformity. So, its better to go with first approach.