Generate random number between 0.1 and 1.0. Python

后端 未结 10 1681
南方客
南方客 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 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
    

提交回复
热议问题