Python Forum
Numpy random number - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: Numpy random number (/thread-4093.html)



Numpy random number - Bryant - Jul-22-2017

I am a beginner of Python. And I am a bit confused by different way of generating random numbers. Appreciate if anyone can explain the difference below:

import numpy as np
a1 = np.random.random((1,4))
a2 = np.random.random(4)
Thank you!


RE: Numpy random number - MTVDNA - Jul-23-2017

The difference is in the output: a2 returns an array of 4 floats, whereas a1 returns a 1x4 multidimensional array of floats, the first dimension in this case being 1.

If you print the output you'll get something like this:
import numpy as np
a1 = np.random.random((1,4))
a2 = np.random.random(4)

print("a1:", a1)
print("a2:", a2)
Output:
a1: [[ 0.59946856  0.98460562  0.2970344   0.93185208]] a2: [ 0.84642216  0.76289462  0.02371878  0.48856006]
See the difference? The way you can access the values is different of course:
# first value of first array in a1
r1= a1[0][0]
# first value of a2
r2 = a2[0]
You can add as many dimensions as you like:
# make a 2 x 4 multidimensional array of random floats
a3 = np.random.random((2,4))
print(a3)
print("")
# make a 2 x 3 x 4 multidimensional array of random floats
a4 = np.random.random((2,3,4))
print(a4)
Output:
[[ 0.24597847 0.31471039 0.66878251 0.12768539] [ 0.82398123 0.97512768 0.39540696 0.43854987]] [[[ 0.27224315 0.77992856 0.54579919 0.24076665] [ 0.56690179 0.2984007 0.4736477 0.45876745] [ 0.31631711 0.8529202 0.10593129 0.44203135]] [[ 0.47631484 0.76030139 0.31148261 0.81140939] [ 0.71954076 0.98883936 0.97953863 0.01995996] [ 0.54762994 0.73041063 0.8126263 0.11215006]]]
If you are not sure how a certain function works, you can just google the name: numpy.random.random and you'll find the documentation:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.random.html