Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Numpy random number
#1
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!
Reply
#2
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/referen...andom.html
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Numpy] How to store different data type in one numpy array? water 7 563 Mar-26-2024, 02:18 PM
Last Post: snippsat
  Numpy returns "TypeError: unsupported operand type(s) for *: 'numpy.ufunc' and 'int'" kalle 2 2,610 Jul-19-2022, 06:31 AM
Last Post: paul18fr
  "erlarge" a numpy-matrix to numpy-array PhysChem 2 2,985 Apr-09-2019, 04:54 PM
Last Post: PhysChem
  counting the occurence of a specified number in a numpy-matrix PhysChem 1 2,405 Apr-03-2019, 01:37 PM
Last Post: PhysChem

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020