Add code to a function that finds roots of an equation using the Newton-Raphson method

50 views (last 30 days)
Angel Washington
Angel Washington on 27 Mar 2020
Answered: Ajay Pattassery on 7 May 2020
Add code to a function that finds roots of an equation using the Newton-Raphson method
  1. Modify the code to display the new "guess" value on each iteration of the loop (i.e., display the value of X). Display the value with at least 15 digits of accuracy after the decimal point. (This will require the use of the fprintf() function.)
  2. Add a counting variable that counts the number of times the loop executes and display this value after the loop terminates.
%this function will find roots of an equation using the Newton-Raphson method
Tolerance = 10e-15;
X = input('Please enter your best guess where a root might be: ');
while abs(f(X)) > Tolerance
X = X - f(X)/f_derivative(X);
end
fprintf('Root: f(%0.15f) = %0.15f\n', X, f(X));
Count = 1
while Count <= 10
disp(Count)
Count = Count + 1
end
I have this newton-raphson code, but I need some guidance because I know there's more to it.

Answers (1)

Ajay Pattassery
Ajay Pattassery on 7 May 2020
Hello,
Consider the following simple example I wrote.
syms f x; %Defined as symbolic variables
f = x.^2 -4*x + 4;
tolerance = .005;
x0 = 16;
count = 0;
while(subs(f,x0) > tolerance) %subs is used here for substituting the value x0 to the function f, differential(f)
x0 = x0 - (subs(f,x0)/subs(diff(f),x0));
fprintf(1,'x0 = %.15f\n',x0)
count = count + 1;
end
fprintf('Number of times loop executed = %d\n',count)
Here I am finding the roots of the simple equation (x-2).^2 = 0
I have incorporated your queries in the above code by taking a sample function f.
  1. The new guess x0 is displayed with the required precision using the fprintf statement.
  2. A counter variable is iterated to find the number of loop executions.
Refer syms, subs, diff, fprintf in the documentation for more details.
Hope this helps!

Community Treasure Hunt

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

Start Hunting!