Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

python - run np.empty for the second time

In the Scipy documents written that :

The function zeros creates an array full of zeros, the function ones creates an array full of ones, and the function empty creates an array whose initial content is random and depends on the state of the memory. By default, the dtype of the created array is float64.

So I was ran this code :

import numpy as np
np.empty((1,2))

And it's return :

array([[  6.92892901e-310,   8.42664136e-317]])

So it's return a random numbers and all of things are great .

But, when I was running that code for the second time (in that shell) it's return a zero array !

np.empty((1,2))
array([[ 0.,  0.]])

And here is the question, why it's return zero array at the second time (instead of random number) ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's not random, it depends on what was saved in the bytes in memory that your computer gave NumPy when it requests some space for the array. If there is something other than zeros in there then these will be interpreted with the requested dtype (seemingly random but a better word would be unpredictable).

In your example you didn't save the first array so the memory for the first array immediatly reused.

>>> import numpy as np
>>> print(id(np.empty((20))))
2545385324992
>>> print(id(np.empty((20))))
2545385324992

Now comes the amazing part: It seems Python (or NumPy or your OS) zeros that memory before it gives it to NumPy again.

If you create a bigger array than it won't be "zero" because it's taken from somewhere else:

>>> print(np.empty((1, 2)))
[[  1.25757479e-311   1.25757479e-311]]
>>> print(np.empty((1, 3)))
[[  4.94065646e-324   9.88131292e-324   1.25757705e-311]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...