Generate random number between 0.1 and 1.0. Python

后端 未结 10 1683
南方客
南方客 2020-12-29 05:23

I\'m trying to generate a random number between 0.1 and 1.0. We can\'t use rand.randint because it returns integers. We have also tried random.uniform(0.1

相关标签:
10条回答
  • 2020-12-29 05:55

    You can use random.randint simply by doing this trick:

    >>> float(random.randint(1000,10000)) / 10000
    0.4362
    

    if you want more decimals, just change the interval to:

    (1000,10000) 4 digits (10000,100000) 5 digits etc

    0 讨论(0)
  • 2020-12-29 05:56

    The standard way would be random.random() * 0.9 + 0.1 (random.uniform() internally does just this). This will return numbers between 0.1 and 1.0 without the upper border.

    But wait! 0.1 (aka ¹/₁₀) has no clear binary representation (as ⅓ in decimal)! So You won't get a true 0.1 anyway, simply because the computer cannot represent it internally. Sorry ;-)

    0 讨论(0)
  • 2020-12-29 06:00

    With the information you've given (including comments thus far), I still fail to see how the university is going to test your program such that it will make a difference if 1.0 appears or not. (I mean, if you're required to generate random floats, how can they require that any particular value appears?)

    OK, so putting the craziness of your requirements aside:

    The fact that the lower bound for your random floats is higher than 0 gives you a disturbingly elegant way to use random.random, which guarantees return values in the interval [0.0, 1.0): Simply keep calling random.random, throwing away any values less than 0.1, except 0.0. If you actually get 0.0, return 1.0 instead.

    So something like

    from random import random
    
    def myRandom():
        while True:
            r = random()
            if r >= 0.1:
                return r
            if r == 0.0:
                return 1.0
    
    0 讨论(0)
  • 2020-12-29 06:00

    Try random.randint(1, 10)/100.0

    0 讨论(0)
提交回复
热议问题