sampling random floats on a range in numpy

前端 未结 3 784
-上瘾入骨i
-上瘾入骨i 2020-12-03 16:45

How can I sample random floats on an interval [a, b] in numpy? Not just integers, but any real numbers. For example,

random_float(5, 10)

would

3条回答
  •  無奈伤痛
    2020-12-03 17:27

    without numpy you can do this with the random module.

    import random
    random.random()*5 + 10
    

    will return numbers in the range 10-15, as a function:

    >>> import random
    >>> def random_float(low, high):
    ...     return random.random()*(high-low) + low
    ...
    >>> random_float(5,10)
    9.3199502283292208
    >>> random_float(5,10)
    7.8762002129171185
    >>> random_float(5,10)
    8.0522023132650808
    

    random.random() returns a float from 0 to 1 (upper bound exclusive). multiplying it by a number gives it a greater range. ex random.random()*5 returns numbers from 0 to 5. Adding a number to this provides a lower bound. random.random()*5 +10 returns numbers from 10 to 15. I'm not sure why you want this to be done using numpy but perhaps I've misunderstood your intent.

提交回复
热议问题