I need to find the fixed point of f. The algorithm is very simple:
- Given X, we calculate f (X)
- If || Xf (X) || below a certain tolerance, exit and return of X, otherwise set X to f (X) and return to 1.
I want to be sure that I do not allocate memory for a new object at each iteration
Now the algorithm is as follows:
iter1 = function(x::Vector{Float64})
for iter in 1:max_it
oldx = copy(x)
g1(x)
delta = vnormdiff(x, oldx, 2)
if delta < tolerance
break
end
end
end
Here g1(x)is a function that sets xtof(x)
But it seems that this cycle highlights a new vector in each cycle (see below).
Another way to write the algorithm is as follows:
iter2 = function(x::Vector{Float64})
oldx = similar(x)
for iter in 1:max_it
(oldx, x) = (x, oldx)
g2(x, oldx)
delta = vnormdiff(oldx, x, 2)
if delta < tolerance
break
end
end
end
where g2(x1, x2)is the function that sets x1to f(x2).
Is the most efficient and natural way to write such an iteration problem?
Edit1: , :
using NumericExtensions
max_it = 1000
tolerance = 1e-8
max_it = 100
g1 = function(x::Vector{Float64})
for i in 1:length(x)
x[i] = x[i]/2
end
end
g2 = function(newx::Vector{Float64}, x::Vector{Float64})
for i in 1:length(x)
newx[i] = x[i]/2
end
end
x = fill(1e7, int(1e7))
@time iter1(x)
x = fill(1e7, int(1e7))
@time iter2(x)
Edit2: copy!
iter3 = function(x::Vector{Float64})
oldx = similar(x)
for iter in 1:max_it
copy!(oldx, x)
g1(x)
delta = vnormdiff(x, oldx, 2)
if delta < tolerance
break
end
end
end
x = fill(1e7, int(1e7))
@time iter3(x)