问题描述
我在写一个函数布尔二维数组:
I was writing a function for boolean 2d arrays:
function foo(A::Array{Bool,2})
...
end
评估和测试它
A = randbool(3,3)
foo(A)
返回
ERROR: 'foo' has no method matching foo(::BitArray{2})
显然, randbool()
生成一个 BitArray
,而我以为 randbool()
将产生一个阵列{布尔}
。
Obviously, randbool()
generates a BitArray
, whereas I assumed randbool()
would yield an Array{Bool}
.
是如何阵列{布尔}
和 BitArray
有关?为什么他们都存在?
How are Array{Bool}
and BitArray
related? Why do they both exist?
我可以写以这样一种方式,它使用一个单一的方法(因为我看不出差异)同时接受输入类型的Foo()
?
推荐答案
这是阵{布尔}
存储每个真/假
值作为布尔
,这是重新在内部psented为 UINT8
$ p $。所以,如果你的阵列有 N
元素,将采取 N
字节来存储它。
An Array{Bool}
stores each true/false
value as a Bool
, which is represented internally as a UInt8
. So if your array has N
elements, it will take N
bytes to store it.
A BitArray
存储每个真/假
值作为单个位,与他们填充的(概念)8到一个单一的 UINT8
。因此,只需要 N / 8
字节来存储阵列。 A BitArray
还定义了处理所有要求的位变换操作为你的方法。
A BitArray
stores each true/false
value as a single bit, with (conceptually) 8 of them packed into a single UInt8
. Consequently, it takes only N/8
bytes to store the array. A BitArray
also has methods defined that handle all the required bit-twiddling operations for you.
根据不同的操作, BitArray
是有时比相应的阵{布尔}
,有时甚至更快的速度较慢。但是,大的性能差异非常小,因此它是有道理的,除非你有特殊原因不能使用 BitArray
秒。但总体而言,他们是相当互换的。
Depending on the operation, BitArray
s are sometimes slower than the corresponding Array{Bool}
, and sometimes faster. But by and large the performance differences are quite small, so it makes sense to use BitArray
s unless you have a specific reason not to. But overall they are fairly interchangeable.
请注意,这两个都是亚型 AbstractArray {布尔}
:
Note that both are subtypes of AbstractArray{Bool}
:
julia> BitArray <: AbstractArray{Bool}
true
julia> Array{Bool} <: AbstractArray{Bool}
true
这可以很容易地编写采取或者一个通用的方法。
This makes it easy to write generic methods that take either one.
这篇关于是什么在朱莉娅阵{}布尔和BitArray之间的差异,他们是如何相关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!