第二次运行np.empty [英] run np.empty for the second time

查看:931
本文介绍了第二次运行np.empty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scipy文档中写道:

In the Scipy documents written that :


函数零创建一个充满零的数组,函数零创建一个完整的数组其中,函数empty创建一个数组,其初始内容是随机的,取决于内存的状态。默认情况下,创建的数组的dtype是float64。

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))

它的回报:

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

所以它返回一个随机数字,所有的东西都很棒。

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

但是,当我第二次运行该代码时(在那个shell中),它返回一个零数组!

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) ?

推荐答案

它不是随机的,它取决于你的计算机在请求某些内容时计算机给出的内存字节中保存的内容 NumPy 阵列的空间。如果那里有零以外的东西,那么这些将被解释为请求的dtype(看似随机但更好的词是不可预测的)。

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

现在来了令人惊奇的部分:似乎Python(或NumPy或你的操作系统)将内存归于NumPy 再次

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]]

这篇关于第二次运行np.empty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆