iteration newton raphson
16 views (last 30 days)
Show older comments
i am having difficulty trying to find an iteration formula using newton-raphson for solving the equation x=cos(2x) and write an m-file for finding the solution whereby x matches cos(2x) to atleast 8 decimal places using format long. can anybody help me?
1 Comment
arushi
on 26 Aug 2024
Hi Sukhraj,
Here is the one example of implemtention for your reference:
function x = solve_cos2x()
% Initial guess
x = 0.5; % You might need to adjust this based on the problem
tolerance = 1e-8;
maxIterations = 1000;
iteration = 0;
while true
% Calculate the function and its derivative
fx = x - cos(2 * x);
dfx = 1 + 2 * sin(2 * x);
% Newton-Raphson update
x_new = x - fx / dfx;
% Check for convergence
if abs(x_new - x) < tolerance
break;
end
% Update x
x = x_new;
% Increment iteration count
iteration = iteration + 1;
if iteration >= maxIterations
warning('Maximum iterations reached without convergence.');
break;
end
end
end
Hope this helps.
Answers (1)
Rahul
on 26 Aug 2024
I understand that you are trying to find an iteration formula using Newton-Raphson for solving the equation x=cos(2x) where x matches cos(2x) to atleast 8 decimal places using format long.
As similarly mentioned by @arushi, you can use a loop for iterating through the values and update the variables using the Newton-Raphson method. An example is as follows:
format long % Initially set the format as long
x_solution = solve_cos_2x();
function x = solve_cos_2x()
syms z % Setting this to get equations
fx = z - cos(2*z);
diff_fx = diff(fx);
x = 0.5; % You can choose a different starting point if needed
tol = 1e-8;
max_iter = 100; % You can adjust max iters
for iter = 1:max_iter
% Newton-Raphson update
x_next = x - double(subs(fx, z, x)) / double(subs(diff_fx, z, x));
if abs(x_next - x) < tol
break;
end
x = x_next;
end
if iter == max_iter
warning('Maximum number of iterations reached without convergence.');
else
fprintf('Converged to x = %.10f in %d iterations\n', x, iter);
end
end
Here I have set 'fx' and 'diff_fx' using symbolic variable 'z'. Hence I was able to use 'diff' function for differentiation.
Using the loop we are updating the Newton-Raphson equation to reach convergence.
You can refer to the following documentations to know more about these functions:
Hope this helps! Thanks.
0 Comments
See Also
Categories
Find more on Symbolic Math Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!