I have this code here where I need to compute the exact jacobian matrix and the approximate jacobian matrix using the newton’s method I have the exact jacobian matrix giving me the correct results but the approximate is giving me the wrong results.I hope that you can help me
function f(v)
n = length(v) # stores the length of v
h = 1/(n+1)
f = zeros(n)
f[1] = -2v[1] + v[2] + (1/4)*exp(v[1])
f[n] = -2v[n] + v[n-1] + (h^2)*exp(v[n])
for i in 2:n-1
local h=1/(i+1)
f[i] = ((v[i+1] - 2v[i] + v[i-1])/h^2) + exp(v[i])
f[i] *= h^2
end
return f
end
epsilon=0.000001
function jacobian_exact(f, x)
n = length(x)
J = zeros(n, n)
for i = 1:n
for j = 1:n
if i == j
h = 1 / (i + 1)
J[i, j] = 2 / h^2 + exp(x[i])
elseif i == j + 1 || i == j - 1
h = 1 / (i + 1)
J[i, j] = -1 / h^2
end
end
end
return J
end
function find_jacobian_matrix(f, x, epsilon)
n = length(x)
J = zeros(n, n)
for j in 1:n
ei = zeros(n)
ei[j] = 1
J[:, j] = (f(x + epsilon*ei) - f(x)) / epsilon
end
return J
end
function newton_method(f, x0, epsilon, max_iter, method::Symbol=:exact)
x = copy(x0)
iter = 0
while norm(f(x)) > epsilon && iter < max_iter
if method == :exact
J = jacobian_exact(f, x)
elseif method == :approximate
J = find_jacobian_matrix(f, x, epsilon)
else
error(“Invalid method specified. Must be :exact or :approximate.”)
end
y = -J \ f(x)
x += y
iter += 1
end
return x
end
initial guess
x0 = [0, 0, 0, 0]
call the function
exact_root = jacobian_exact(f, x0) \ f(x0)
approx_root = find_root(f, x0, epsilon, 100, :approximate)
display the results
println("Exact Root: ", exact_root)
println("Approximate Root: ", approx_root)