“== 和 === 在 Julia 数组和向量中的区别”

huangapple go评论62阅读模式
英文:

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

然而,av,尽管它们具有相同的内容,但它们不具有相同的内存位置(你可能会得到不同的值):

julia> pointer(a)
Ptr{Int64} @0x000001e6025161b0

julia> pointer(v)
Ptr{Int64} @0x000001e602524f90

所以它们是可以区分的,因此在使用 === 进行比较时会得到不同的结果。

== 不同,因为它只考虑值的相等性。在这种情况下,av 是相同形状并存储相同数字的数组,因此使用 == 比较它们会返回 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

原因是 a2a 变量指向同一个数组(即内存中的相同位置的数组)。

英文:

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

huangapple
  • 本文由 发表于 2023年2月19日 22:16:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75500755.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定