The homework task sounds something like this
Generate a random vector of 4*n uniform integer numbers ranging from 1
to 6, reshape this vector into an array with four rows and n columns,
representing the outcome of n throws with four dice….
I’ve come up with the following solution :
import numpy as np
num = 10
v = np.random.randint(1,7,(num,4))
So far so good, but I noticed that my generated array is in the 4 x n shape at the point of creation, and it has not been reshaped. I’ve considered the following as well :
v = np.random.randint(1,7,(4*num))
z = np.reshape(v,(num,-4))
Is there a difference between these two in terms of how v is built up? From a couple of print statements, they seem the same (in terms of shape) but I could not make sense of the documentation.
Both ways are equivalent, although your homework task seems to require to create a 1D array first and reshape it to 2D afterwards.
NumPy allocates a single memory block for
num*4integers, fills them with random values drawn uniformly from the interval[1, 7), then returns an array that interprets this 1D array as a “C-contiguous” 2D array withnumrows and4columns*.This does the same thing, but more explicitly:
vstill is a 1D array, andzis a view onv, interpreting the same data as 2D array. This means that changing a value invwill also change it inz, since both arrays point to the same memory.The
-4does not make sense — array dimensions cannot be negative. NumPy does support one dimension to take the special value-1, which means “infer the dimension automatically from the size of the array”. It seems that it also accepts other negative numbers for the same purpose but that is an undocumented feature. That means it might as well be a bug and removed from future versions. Either reshape it explicitly to(num, 4)or use(num, -1)to let NumPy auto-discover the 4.Please also note that your assignment says “four rows and n columns”, whereas your arrays will have
numrows and 4 columns.*) For example, the 1D array
[ 1 2 3 4 5 6 7 8 ]is reshaped to: