英文:
Difference between == and === in Julia arrays and vectors
问题
为什么 `typeof(a) == typeof(v)` 和 `typeof(a) === typeof(v)` 都为真,但 `a == v` 为真,`a === v` 为假呢?
英文:
Why is it that typeof(a) == typeof(v)
is true and typeof(a) === typeof(v)
is also true, but a == v
is true and a === v
is false?
julia> a = Array([1,2,3])
3-element Vector{Int64}:
1
2
3
julia> v = Vector([1,2,3])
3-element Vector{Int64}:
1
2
3
julia> typeof(a) == typeof(v)
true
julia> typeof(a) === typeof(v)
true
julia> a == v
true
julia> a === v
false
答案1
得分: 4
===
确定比较的对象是否完全相同,即没有程序可以将它们区分开。
所以 typeof(a)
和 typeof(v)
是相同的(类型都是 Vector{Int64}
(别名为 Array{Int64, 1}
)),所以它们使用 ===
进行比较会返回 true
。
然而,a
和 v
,尽管它们具有相同的内容,但它们不具有相同的内存位置(你可能会得到不同的值):
julia> pointer(a)
Ptr{Int64} @0x000001e6025161b0
julia> pointer(v)
Ptr{Int64} @0x000001e602524f90
所以它们是可以区分的,因此在使用 ===
进行比较时会得到不同的结果。
==
不同,因为它只考虑值的相等性。在这种情况下,a
和 v
是相同形状并存储相同数字的数组,因此使用 ==
比较它们会返回 true
。
从某种意义上说,当进行比较时,==
比 ===
宽松一些。
请注意,如果你使用元组而不是数组:
julia> t1 = (1, 2, 3)
(1, 2, 3)
julia> t2 = (1, 2, 3)
(1, 2, 3)
julia> t1 === t2
true
原因是元组是不可变的,所以即使你两次创建它们,它们在这种情况下被认为是相同的,当使用 ===
进行比较时它们是不可区分的。
最后请注意,如果你这样写:
julia> a2 = a
3-element Vector{Int64}:
1
2
3
julia> a2 === a
true
原因是 a2
和 a
变量指向同一个数组(即内存中的相同位置的数组)。
英文:
===
determines whether compared objects are identical, in the sense that no program could distinguish them.
So typeof(a)
and typeof(v)
are identical (the type is Vector{Int64}
(alias for Array{Int64, 1}
) in both cases) so they compare with ===
as true
.
However a
and v
, although they have the same contents do not have the same memory location (you will likely get different values):
julia> pointer(a)
Ptr{Int64} @0x000001e6025161b0
julia> pointer(v)
Ptr{Int64} @0x000001e602524f90
so they are distinguishable, thus different when compared by ===
.
The ==
is different as it considers just the equality of values. In this case a
and v
are arrays of the same shape and storing the same numbers, so comparing them using ==
returns true
.
In a sense ==
is less strict than ===
when doing a comparison.
Note that e.g. if you used tuples instead of arrays:
julia> t1 = (1, 2, 3)
(1, 2, 3)
julia> t2 = (1, 2, 3)
(1, 2, 3)
julia> t1 === t2
true
The reason is that tuples are not mutable so even if you create them twice they are in this case considered identical when being compared with ===
(they are not distinguishable).
Finally notice that if you write:
julia> a2 = a
3-element Vector{Int64}:
1
2
3
julia> a2 === a
true
The reason is that a2
and a
variables point to the same array (i.e. array having the same location in memory).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论