iteration newton raphson
17 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaire
arushi
le 26 Août 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.
Réponses (1)
Rahul
le 26 Août 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 commentaires
Voir également
Catégories
En savoir plus sur Symbolic Math Toolbox dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!