When using Vector{T}(undef,n) constructor, what are the values set to?

Hi!

If T = Float64, I observe that the values most often are set as some very small number, but is it possible for it to be a number such as “0.1”,“5” etc.?

The reason I ask is that I just found out that some code I had would produce unstable results if I used the undef initializer to pre-initialize the vector compared to using zeros(Float64,n).

By unstable I mean that the algorithm I am using would change results based on the initialized values of the undef vector.

Kind regards

The values you get are whatever is in memory. They are actually not set to anything at all, so the values are completely undefined.

If you want your data initialized to 0, then use zeros. For other values, use fill!.

See also Faster zeros with calloc

1 Like

Ah okay, thanks for the clarification. So it just takes any suitable amount of space available, without consideration of the previous data there, got it.

Kind regards

zeros is basically just

a = Vector{T}(undef, n)
fill!(a, zero(T))

Using undef does not clear the space for you. You use undef when you are going to manually initialize the values anyways, so there is no point in trying to fill it with zeros.

2 Likes