Hi, my name is Terry, and I’d like to propose a small function that could be added into the Python’s “random” module.

 

This function is for generating a random float/decimal number. I would like to know if there’s such function that does the same thing, if there is, please point out to me. If not, I would like to ask you developers to add this function into future Python versions.

 

The function code is as follow:

 

from random import *

 

def randfloat(x , y , maxfloatpt=None):

    if x > y:

        x , y = y , x

    lenx = len(str(x))

    leny = len(str(y))

    intx = int(x)

    inty = int(y)

    bigger = max(lenx,leny)

    if maxfloatpt == None:

        if bigger == lenx:

            intxlen = len(str(intx))

            maxfloatpt = len(str(x)[intxlen:])

        elif bigger == leny:

            intylen = len(str(inty))

            maxfloatpt = len(str(y)[intylen:])

        else:

            pass

   else:

        pass

    num = randint(intx , inty)

    num = str(num)

    num = '%s.' % num

    for i in range(0 , maxfloatpt):

        flnum = randint(0 , 9)

        str(flnum)

        num = '%s%s' % (num , flnum)

    return float(num)

       

P.S.: If the indent has anything wrong, just correct me, thx!

 

P.P.S.: The function is tested, it’s working 😊