Julia位陣列的再探

lt發表於2017-04-12

上次測試不太完善,得出錯誤的結論3.位陣列的空間不是位元組,而是雙位元組
其實BitAarry在0.51版文件中有詳細說明。

BitArrays
BitArrays are space-efficient “packed” boolean arrays, which store one bit per boolean value. They can be used similarly to Array{Bool} arrays (which store one byte per boolean value), and can be converted to/from the latter via Array(bitarray) and BitArray(array), respectively.

• Vector (a.k.a. 1-dimensional Array)
• BitVector (a.k.a. 1-dimensional BitArray)

那就是說1維BitArray與BitVector實質上是一樣的。在0.6版的聯機幫助中:

help?> BitVector
search: BitVector

  BitArray(dims::Integer...)
  BitArray{N}(dims::NTuple{N,Int})

BitArray結構需要佔用一定的基本空間。在元素較少的時候,也要至少8位元組。

julia> map(x->(x,sizeof(BitArray(x))),[1,2,4,8,16,32,64,128,256])
9-element Array{Tuple{Int32,Int32},1}:
 (1, 8)
 (2, 8)
 (4, 8)
 (8, 8)
 (16, 8)
 (32, 8)
 (64, 8)
 (128, 16)
 (256, 32)

文件說Array建構函式返回的是未初始化的值,

Array(dims)
Array{T}(dims) constructs an uninitialized dense array with element type T. dims may be a tuple or a series of integer arguments. The syntax Array(T, dims) is also available, but deprecated.

聯機幫助也是

help?> BitArray   
search: BitArray

  BitArray(dims::Integer...)  
  BitArray{N}(dims::NTuple{N,Int})  

  Construct an uninitialized BitArray with the given dimensions. Behaves identically to the Array constructor.  

在實際操作中,Array明顯返回不確定的值。

julia> Array(Int8,10),Array(Int16,10)
(Int8[-32, 78, 7, 19, -112, 74, 10, 15, -16, 78], Int16[66, 0, 105, 0, 116, 0, 65, 0, 114, 0])

雖然BitArray觀察到的都是false,為了確保得到需要的值,還是用trues和false保險。

julia> BitArray(10),trues(10),falses(10)
(Bool[false, false, false, false, false, false, false, false, false, false], 
Bool[true, true, true, true, true, true, true, true, true, true], 
Bool[false, false, false, false, false, false, false, false, false, false])

0.5版的聯機幫助中顯示BitArray有len成員,實際測試Aarry沒有。

julia> BitArray(2, 2)
2××2 BitArray{2}:
 false  false
 false  false

julia> BitArray(3, 1)
3××1 BitArray{2}:
 false
 false
 false

julia> ba=BitArray(30);

julia> ba.len
30

julia> ia=Array{Int}(30);

julia> ia.len
ERROR: type Array has no field len

相關文章