0

I am looking at np.empty() and everywhere it states 'Return a new array of given shape and type, without initializing entries.'

However every time I print np.empty() I see it already has random values assigned to it. What am I missing here?

A second question: in case np.empty() uses random values, how is it that the below code always returns the same value?

print(np.empty((3,2))) 

[[ 1.   5.4]
[ 9.8 14.2]
[18.6 23. ]]
sjaustirni
  • 3,056
  • 7
  • 32
  • 50
user1906450
  • 517
  • 1
  • 6
  • 19
  • 1
    numpy is just grabbing a block of memory without doing anything to the values in there. That's why you see random numbers. I contrast, `np.zeros` grabs a block of memory and assigns all zeros. – timgeb Jan 06 '19 at 13:20
  • thnk u.. timgeb... why do i get the same values every time though?? – user1906450 Jan 06 '19 at 13:25
  • 1
    When you see identical values, numpy likely grabbed the same block of memory. – timgeb Jan 06 '19 at 13:28
  • That's a bad duplicate for this user. It focuses on an irrelevant detail. – hpaulj Jan 06 '19 at 16:58
  • 1
    This is roughly the same difference between [`malloc` and `calloc`](https://stackoverflow.com/questions/1538420/difference-between-malloc-and-calloc): the latter zero-initializes; the former does not. – Kevin Ji Jan 06 '19 at 17:11
  • @hpaulj not sure i understand.. you mean duplicate as in duplicate question? – user1906450 Jan 06 '19 at 18:20
  • I was referring to the first link given when this was flagged as a duplicate. I found a better duplicate (so I think). In any case, the pattern that you noticed is just an implementation detail. It's ok to use `np.empty` if you plan on filling ALL elements of the array, otherwise use `np.zeros`, `ones` or `full`. Another way to put it is - `print(empty([2,2]))` does not tell us anything useful. – hpaulj Jan 06 '19 at 18:59

0 Answers0