How to write a code for Newton Raphson method

1 回表示 (過去 30 日間)
Ashley Warnes
Ashley Warnes 2017 年 2 月 11 日
編集済み: Jan 2017 年 2 月 11 日
I need to write a code to solve newton raphson method to 4dp. Using the function f(x)=x^3-2*x+2 and starting value x=-1.5, I've got the code below but can't seem to solve it as x(n) turns into an array rather than just the value of x.
x(1)=-1.5;
n=2;
while abs(x^3-2*x+2)>0.0001
x(n)=x(n-1)+((((x(n-1))^3)-2*(x(n-1))+2)/(3*((x(n-1))^2)-2));
n=n+1;
end
x

回答 (1 件)

Jan
Jan 2017 年 2 月 11 日
編集済み: Jan 2017 年 2 月 11 日
A vectors looks nice as output. All you have to change is, that you check the last element for the while condition only:
while abs(x(end)^3 - 2 * x(end) + 2) > 0.0001
But the obtained sequence does not converge. It seems like there is a bug in the Newton-Raphson formula, a + instead of a - .
Avoid an infinite loop by setting a maximum iteration count, e.g.:
if n > 1e6
error('Sequence does not converge');
end

カテゴリ

Help Center および File ExchangeNewton-Raphson Method についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by