Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between `zero(eltype(x))` and `zero(x)` in Julia

In ‘Julia High Performance’ (2nd Ed.), the author gives the following example to explain how to obtain type stability in loops:

function simdsum_fixed(x)
    s = zero(eltype(x))
    @simd for v in A
        s += v
    end
    return s
end

In a previous example, with different code they simply use zero(x). I’ve therefore tried the same function without eltype() as below (simdsum_fixed_b). They seem to work in the same way.

function simdsum_fixed_b(x)
    s = zero(x)
    @simd for v in A
        s += v
    end
    return s
end

How is then zero(eltype(x)) different from zero(x)? What is the advantage of using the first over the second?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance.

>Solution :

Use zero(eltype(x)) if x is a container (e.g. a vector) and you want additive identity of its elements. Use zero(x) if you want to get the additive identity of x itself.

Example with vector as here the difference is most clearly visible:

julia> x = [1, 2, 3]
3-element Vector{Int64}:
 1
 2
 3

julia> zero(x)
3-element Vector{Int64}:
 0
 0
 0

julia> zero(eltype(x))
0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading