Newton Raphson method help

2 vues (au cours des 30 derniers jours)
Oskar Nordström
Oskar Nordström le 14 Oct 2020
Réponse apportée : KSSV le 14 Oct 2020
I need to find an answer to this question: Find the root of x^3 + 2*x^2 - 2 = 0 between 0 and 1. i've written this code but when i run the code i get: "Error: File: Uppg12.m Line: 22 Column: 26. Invalid use of operator.". If anyone knows how the Newton raphson mothod works and how i can fix this code, pleas help!
Btw i'm new to matlab and when i read about the Newton method in our book they recomended this solution:
function [x1,n] = newton(fun,dfun,x0,tol)
n = 0;
dx = 1e30;
while abs(dx) > tol & n < 50
dx = fun(x0)/dfun(x0);
x1 = x0 - x1;
x0 = x1;
n = n +1;
end
i can't seem to aply this solution to my problem. This is what i wrote:
syms x
n = 0;
x0 = 0.5;
tol = 1e-13;
dx = 1e30;
function y = fun(x)
y = x.^3 + 2.*x.^2 - 2;
end
function dy = dfun(x)
dy = 3.*x.^2 + 2.*x;
end
function [x1,n] = newton(@fun,@dfun,x0,tol)
while abs(dx) > tol && n < 50
dx = fun(x0)./dfun(x0);
x1 = x0 - dx;
x0 = x1;
n = n + 1;
end
end

Réponse acceptée

KSSV
KSSV le 14 Oct 2020
fun = @(x) x^3 + 2*x^2 - 2;
dfun = @(x) 3*x^2 + 4*x ;
function [x1,n] = newton(fun,dfun,x0,tol)
n = 0;
x0 = rand ; % initial guess
tol = 10^-5 ; % tolerance
while abs(dx) > tol && n < 50
x1 = x0-fun(x0)/dfun(x0);
dx = abs((x1-x0)/x0)
x0 = x1;
n = n +1;
end
You can check the solution using:
fun(x1)

Plus de réponses (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by