Generate random array of floats between a range

前端 未结 8 1737
孤独总比滥情好
孤独总比滥情好 2020-12-02 15:04

I haven\'t been able to find a function to generate an array of random floats of a given length between a certain range.

I\'ve looked at Random sampling but no funct

相关标签:
8条回答
  • 2020-12-02 15:28

    Why not to combine random.uniform with a list comprehension?

    >>> def random_floats(low, high, size):
    ...    return [random.uniform(low, high) for _ in xrange(size)]
    ... 
    >>> random_floats(0.5, 2.8, 5)
    [2.366910411506704, 1.878800401620107, 1.0145196974227986, 2.332600336488709, 1.945869474662082]
    
    0 讨论(0)
  • 2020-12-02 15:36

    Why not use a list comprehension?

    In Python 2

    ran_floats = [random.uniform(low,high) for _ in xrange(size)]
    

    In Python 3, range works like xrange(ref)

    ran_floats = [random.uniform(low,high) for _ in range(size)]
    
    0 讨论(0)
  • 2020-12-02 15:41

    There may already be a function to do what you're looking for, but I don't know about it (yet?). In the meantime, I would suggess using:

    ran_floats = numpy.random.rand(50) * (13.3-0.5) + 0.5
    

    This will produce an array of shape (50,) with a uniform distribution between 0.5 and 13.3.

    You could also define a function:

    def random_uniform_range(shape=[1,],low=0,high=1):
        """
        Random uniform range
    
        Produces a random uniform distribution of specified shape, with arbitrary max and
        min values. Default shape is [1], and default range is [0,1].
        """
        return numpy.random.rand(shape) * (high - min) + min
    

    EDIT: Hmm, yeah, so I missed it, there is numpy.random.uniform() with the same exact call you want! Try import numpy; help(numpy.random.uniform) for more information.

    0 讨论(0)
  • 2020-12-02 15:45

    This is the simplest way

    np.random.uniform(start,stop,(rows,columns))
    
    0 讨论(0)
  • 2020-12-02 15:47

    The for loop in list comprehension takes time and makes it slow. It is better to use numpy parameters (low, high, size, ..etc)

    import numpy as np
    import time
    rang = 10000
    tic = time.time()
    for i in range(rang):
        sampl = np.random.uniform(low=0, high=2, size=(182))
    print("it took: ", time.time() - tic)
    
    tic = time.time()
    for i in range(rang):
        ran_floats = [np.random.uniform(0,2) for _ in range(182)]
    print("it took: ", time.time() - tic)
    

    sample output:

    ('it took: ', 0.06406784057617188)

    ('it took: ', 1.7253198623657227)

    0 讨论(0)
  • 2020-12-02 15:50

    Alternatively you could use SciPy

    from scipy import stats
    stats.uniform(0.5, 13.3).rvs(50)
    

    and for the record to sample integers it's

    stats.randint(10, 20).rvs(50)
    
    0 讨论(0)
提交回复
热议问题