Difference between functions generating random num

2020-02-09 05:27发布

问题:

I am trying to understand what is the difference, if any, between these functions:

numpy.random.rand()

numpy.random.random()

numpy.random.uniform()

It seems that they produce a random sample from a uniform distribution. So, without any parameter in the function, is there any difference?

回答1:

numpy.random.uniform(low=0.0, high=1.0, size=None) - uniform samples from arbitrary range

Draw samples from a uniform distribution.
Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform.

numpy.random.random(size=None) - uniform distribution between 0 and 1

Return random floats in the half-open interval [0.0, 1.0).
Results are from the “continuous uniform” distribution over the stated interval. To sample Unif[a, b), b > a multiply the output of random_sample by (b-a) and add a:
(b - a) * random_sample() + a

numpy.random.rand(d0, d1, ..., dn) - Samples from a uniform distribution to populate an array of a given shape

Random values in a given shape.
Create an array of the given shape and propagate it with random samples from a uniform distribution over [0, 1).

To answer your other question, given all default parameters all of the functions numpy.random.uniform, numpy.random.random, and numpy.random.rand are identical.



回答2:

Short answer

Without parameters, the three functions are equivalent, producing a random float in the range [0.0,1.0).

Details

numpy.random.rand is a convenience function that accepts an arbitrary number of parameters as dimensions. It's different from the other numpy.random functions, numpy.zeros, and numpy.ones also, in that all of the others accept shapes, i.e. N-tuples (specified as Python lists or tuples). The following two lines produce identical results (the random seed notwithstanding):

import numpy as np
x = np.random.random_sample((1,2,3)) # a single tuple as parameter
x = np.random.rand(1,2,3) # integers as parameters

numpy.random.random is an alias for numpy.random.random_sample.

numpy.random.uniform allows you to specify the limits of the distribution, with the low and high keyword parameters, instead of using the default [0.0,1.0).