writing a script to find roots using Newton-Raphson Method in Matlab, how ?

조회 수: 2 (최근 30일)
zee 00
zee 00 2015년 12월 2일
답변: Yash 2024년 8월 27일
i need to write a code that can calculates the square root of a positive real number, it has to ask N which is the positive real number and then ask for x1 which is the initial best guess for the root and then ask for the maximum number of iterations ask finally ask for E which is the acceptable percentage tolerance, the script has to keep calculating until the max number of iteration is reached or the approx error is less than the acceptable tolerance. i am given that Xi+1 = 1/2[Xi+(N/Xi)] and the approx error is |(Xi+1 - Xi)/Xi+1|x100,, thank you in advance
  댓글 수: 1
Geoff Hayes
Geoff Hayes 2015년 12월 2일
zee - you must have discussed the algorithm in class (else you can find it using your favourite search engine). Once you have the algorithm (and understand it) try implementing it in MATLAB. If you encounter any problems or errors, then post the code and your issue to your question so that you can receive some help.

댓글을 달려면 로그인하십시오.

답변 (1개)

Yash
Yash 2024년 8월 27일
Hi Zee,
There could be various methods to achieve this, I have attached one approach below for your reference. Please verify the actual algorithm discussed in your classes with the code:
% Square Root Calculation using Iterative Method
% Prompt the user for inputs
N = input('Enter the positive real number (N): ');
x1 = input('Enter the initial best guess for the root (x1): ');
maxIterations = input('Enter the maximum number of iterations: ');
E = input('Enter the acceptable percentage tolerance (E): ');
% Initialize variables
iteration = 0;
approxError = inf; % Start with an infinite error to enter the loop
x_current = x1;
% Iterative calculation using the given formula
while iteration < maxIterations && approxError > E
% Calculate the next approximation
x_next = 0.5 * (x_current + (N / x_current));
% Calculate the approximate error
approxError = abs((x_next - x_current) / x_next) * 100;
% Update the current approximation
x_current = x_next;
% Increment the iteration counter
iteration = iteration + 1;
% Display the current iteration and approximation
fprintf('Iteration %d: x = %.10f, Approx. Error = %.10f%%\n', iteration, x_current, approxError);
end
% Display the final result
fprintf('\nEstimated square root of %.10f is %.10f after %d iterations with approx. error %.10f%%\n', N, x_current, iteration, approxError);
I hope this helps you in implementing the algorithm.

카테고리

Help CenterFile Exchange에서 Newton-Raphson Method에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by