Filter löschen
Filter löschen

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

4 Ansichten (letzte 30 Tage)
zee 00
zee 00 am 2 Dez. 2015
Beantwortet: Yash am 27 Aug. 2024
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 Kommentar
Geoff Hayes
Geoff Hayes am 2 Dez. 2015
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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Yash
Yash am 27 Aug. 2024
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.

Community Treasure Hunt

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

Start Hunting!

Translated by