Fun and creative ways of generating random numbers in python
Here I'm going to show some creative and fun ways of generating random numbers without using random
package in python.
Example 1 - Generating random number in range 0-9
When we call time()
function of the package time
, it returns floating point number - current time in seconds since the Epoch:
>>> time.time()
3392849227.6848479
We are interested in fractional-part, which is displaying milliseconds, and changing so fast. We need the rightmost part. So, here is the function:
import time
def gen_number() -> int:
return int(str(time.time())[-2])
You may ask why we are using -2
instead of -1
for string indexing. We cannot get 0
if we use -1 as index, because trailing zeros are truncated in the floating part.
Let's test our gen_number
function which generates numbers from 0 to 9 randomly:
results = [0 for i in range(10)]
for _ in range(10**5):
results[gen_number()] += 1
print(results)
Output:
[10007, 10033, 12136, 9972, 9528, 9360, 9017, 10051, 6658, 13238]
Here we can see that the distribution is quite good.
True
/False
or 0
/1
Example 2 - Generating Here is the another example using time
package, which generates True
and False
(or 1
and 0
) randomly:
import time
def gen_tf() -> bool:
return time.time() == time.time()
False
is increased. Whereas, in high-end computers, we almost don't get False
results.
Lets test the gen_tf
function:
results = {True: 0, False: 0}
for _ in range(10**5):
results[gen_tf()] += 1
print(results)
The results will be different. For example if we run this code on online python interpreters like Python.org, Programiz, or Onlinegdb, we get result like:
{True: 55577, False: 44423}
{True: 50281, False: 49719}
The distribution is nearly equal. But when you run this on the high-end computers, results will look like (in my case):
{True: 99990, False: 10}
To increase the chances of getting False
we can use datetime.now().timestamp()
instead of time.time()
:
from datetime import datetime
def gen_tf() -> bool:
return datetime.now().timestamp() == datetime.now().timestamp()
Because dateime.now().timestamp()
has two function calls, it executes slower, so the probabilies of getting False
are increased