Newton Method code has infinite loop and an unrecognizable function x_n.
4 ビュー (過去 30 日間)
古いコメントを表示
I have been having issues figuring out how to fix the code. The objective here is to use the Newton Method to find the root of the equation between 1 and 3 for the function f(x) = x^3 - x^2 - 4*x +1. We do that by coding a function named root_newton that takes the parameter x, the initial guess xo, and returns the calculated root. The function must also apply the Newton Method until the absolute value of the function is less than 0.0001.
I believe I may have not created an end condition for the while and for loop, but I have tried to type different lines of code and this was the latest one I created. Any suggestions?
function y = root_newton(x)
b = x^3 - x^2 - 4*x + 1;
b_prime = diff(b);
xo = 2;
while abs(xo) > 0.0001;
n = 0
for i = 1:n;
x_n = (x*i)+1
x_n = (x*i) - ((y(x*i)) / (b_prime(x*i)))
xo = (x_n)^3 - (x_n)^2 - 4*(x_n) +1;
end
y = x_n
end
0 件のコメント
回答 (1 件)
Chandler Hall
2022 年 11 月 12 日
編集済み: Chandler Hall
2022 年 11 月 12 日
The code you have so far will require a number of revisions before it gives the desired result. The principal issue is that the equations in the loop are implemented too literally with not enough regard for the Matlab syntax.
A first step would be to define our target function more explicitly:
function y = f(x)
y = x^3 - x^2 - 4*x + 1;
end
And I assume you are expected to find the derivative manually. The diff function is not going to serve properly here. You could define it to be used conveniently in the algorithm:
function y = f_prime(x)
% differentiate the polynomial
y =
end
Regarding the primary function root_newton, is the expected output of root_newton(2) the result of the algorithm with x0 = 2? In such a case, it would be reasonable to proceed:
% calling the return value 'y' is arbitrary. There's usually a name that is
% more descriptive and convenient
function x_n = root_newton(x_0)
x_n = x_0; % establish the initial condition of the algorithm (together with the above functions)
while abs(f(x_n)) > 0.0001
x_n = ...
end
end
Here, the loop condition abs(f(x_n)) is indeed equivalent to your code, but the intention is more direct. The final step is to fix the iteration. When implementing interative and recursive style algorithms, generally there is no reference to an "n+1", you just need to directly update the x_n variable with the equation for the next iteration. The nested for loop is superfluous. The iteration count n is essentially determined by the threshold which is set at 0.0001 and ultimately is not worth keeping track of unless specifically called for.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!