# Round inplace?

What is the reason that there are not `round!` functions? Is it not possible to do that type of operation in place? It seems like it is no different than `replace!` (which exists) and the thing you are replacing with is simply a rounded version of the original value (without the need to search for it).

No operations on floating-point numbers are in-place since they are immutable.

1 Like

Sorry, I mean for vectors

Because its not common to need it and it’s a one-liner to write it yourself using broadcasting, I guess.

`v .= round.(v)`

4 Likes

Fair enough. I am rounding a vector with >100M values so it takes a bit to finish and so this came to mind.

`replace!` isn’t so easy to replace with a dotted version, while in-place `round` is trivial to write with dots.

I guess the real question is why you need this – i.e. what you will do with the 100M results.

It is worth noting that the @dpsanders answer use dot fusion to not create an intermediary array so, in that aspect, it is as efficient as a `round!` could get.

1 Like

Almost:

``````julia> function round1!(v)
v .= round.(v)
end
round1! (generic function with 1 method)

julia> function round2!(v)
for i in eachindex(v)
v[i] = round(v[i])
end
end
round2! (generic function with 1 method)

julia> v = 10 .* rand(1000);

julia> function round2!(v)
for i in eachindex(v)
@inbounds v[i] = round(v[i])
end
end
round2! (generic function with 1 method)

julia> @btime round1!(\$v);
69.519 ns (0 allocations: 0 bytes)

julia> @btime round2!(\$v);
66.269 ns (0 allocations: 0 bytes)

``````

Ok, but:

``````julia> using BenchmarkTools
julia> function round1!(v)
@inbounds v .= round.(v)
end
julia> function round2!(v)
for i in eachindex(v)
@inbounds v[i] = round(v[i])
end
end
julia> import Random
julia> Random.seed!(0);
julia> v = 1000 .* rand(100000);
julia> @btime round1!(\$v)
20.245 μs (0 allocations: 0 bytes)
julia> @btime round2!(\$v)
19.232 μs (0 allocations: 0 bytes)
julia> @btime round1!(\$v)
19.132 μs (0 allocations: 0 bytes)
julia> @btime round2!(\$v)
19.166 μs (0 allocations: 0 bytes)
julia> @btime round1!(\$v)
19.512 μs (0 allocations: 0 bytes)
julia> @btime round2!(\$v)
19.248 μs (0 allocations: 0 bytes
``````

Seems negligible to me.

2 Likes