Skip to content

Instantly share code, notes, and snippets.

@GooDeeJAY
Last active August 3, 2022 06:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GooDeeJAY/3364e4e29d5e518057d9827f03668b9d to your computer and use it in GitHub Desktop.
Save GooDeeJAY/3364e4e29d5e518057d9827f03668b9d to your computer and use it in GitHub Desktop.
Creative and fun ways of generating random numbers

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.

Example 2 - Generating True/False or 0/1

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()

⚠️ This is hardware dependent. In slower machines, chances of getting 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment