Python Forum

Full Version: Why there is a star inside randn?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I have question about generating a linear model from random data. I suppose that by default, the value of size in the dnorm function is one. When this function is called with N=100, size becomes 100. Am I correct? If so, what is the reason for having the * symbol in np.randn(*size)? What is the different between this and np.randn(size)?

def dnorm(mean, variance, size=1):
  if isinstance(size, int):
      size = size,
  return mean + np.sqrt(variable) * np.random.randn(*size)

N = 100
X = np.c_[dnorm(0, 0.4, size=N),
          dnorm(0, 0.6, size=N)]
When size is of integer type, there is no difference. However, when size is a tuple of integers, dnorm generates nd-random array. So, dnorm function allows you to pass size as an integer value (in case of one-dimensional array) and as a tuple of integers, if you want to generate nd-array.
Thanks. How can I tell if size is an integer or a tuple of integers?

Is the number of elements in the tuple corresponds to the dimension of the nd-array? For example if size is a tuple of (x, y), then np.random.randn(*size) generates a 2 dimensional array of x rows and y columns. If size is a tuple of three elements (x, y, z), then np.random.randn(*size) generates a 3 dimensional array of x rows, y columns and z levels?
(Mar-05-2020, 02:20 PM)new_to_python Wrote: [ -> ]Thanks. How can I tell if size is an integer or a tuple of integers?
In the line #2 in your code you check if size is of integeter type. If size is integer, the next line (#3) size = size,, which is equivalent to size = (size, ), turns size into a tuple (of len 1).
So, it doesn't matter, what you assign to size parameter : integer or tuple. Passing alone integer as size variable turns it to a tuple of len 1 before "sending" it to randn. If size originally is a tuple, it doesn't change and pass to randn function as is.
However, if someone pass a tuple consiting not only of integers, e.g. (1, 'bob') or (1, 3.4), this likely lead to an exception in the randn function. Therefore, you probably can wish to do additional checks, e.g. if all elements of a tuple passed as size variable are integers.

(Mar-05-2020, 02:20 PM)new_to_python Wrote: [ -> ]Is the number of elements in the tuple corresponds to the dimension of the nd-array? For example if size is a tuple of (x, y), then np.random.randn(*size) generates a 2 dimensional array of x rows and y columns. If size is a tuple of three elements (x, y, z), then np.random.randn(*size) generates a 3 dimensional array of x rows, y columns and z levels?
You are right. If you pass a tuple of integers of len N, randn returns a N-dimensional random array.
Understood. Thank you.