Show Sidebar Hide Sidebar

Random

How to sample numbers uniformly between 0 and 1.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

Imports

This tutorial imports Numpy.

In [1]:
import plotly.plotly as py
import plotly.graph_objs as go

import numpy as np

Random and Rand

np.random.random() and np.random.rand() are identical functions used to return numbers sampled uniformly from the half-open interval $[0, 1)$. np.random.rand() is just a convenience function which is an instance of a subclass of the class gdb.Function. By default the argument parameter size is set to None which means that a single random number is returned. size can be entered as a shape, which is just a tuple of integers representing the dimentions of the array to be outputted.

In [2]:
import plotly.plotly as py
import plotly.graph_objs as go

num_of_points = 20
random_array = np.random.random((num_of_points))

trace1 = go.Scatter(
    x=[j for j in range(len(random_array))],
    y=random_array,
    mode='markers',
    marker = dict(
        size=15,
        color=random_array,
        colorscale='Viridis'
    ),
    name='random array'
)

py.iplot([trace1], filename='numpy-random')
Out[2]:
In [2]:
help(np.random.random)
Help on built-in function random_sample:

random_sample(...)
    random_sample(size=None)
    
    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 :math:`Unif[a, b), b > a` multiply
    the output of `random_sample` by `(b-a)` and add `a`::
    
      (b - a) * random_sample() + a
    
    Parameters
    ----------
    size : int or tuple of ints, optional
        Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
        ``m * n * k`` samples are drawn.  Default is None, in which case a
        single value is returned.
    
    Returns
    -------
    out : float or ndarray of floats
        Array of random floats of shape `size` (unless ``size=None``, in which
        case a single float is returned).
    
    Examples
    --------
    >>> np.random.random_sample()
    0.47108547995356098
    >>> type(np.random.random_sample())
    <type 'float'>
    >>> np.random.random_sample((5,))
    array([ 0.30220482,  0.86820401,  0.1654503 ,  0.11659149,  0.54323428])
    
    Three-by-two array of random numbers from [-5, 0):
    
    >>> 5 * np.random.random_sample((3, 2)) - 5
    array([[-3.99149989, -0.52338984],
           [-2.99091858, -0.79479508],
           [-1.23204345, -1.75224494]])

Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.