While loop not starting

1 view (last 30 days)
Karthi Ramachandran
Karthi Ramachandran on 22 Jan 2020
I am trying to implement a newtons method to find the root of a function. When i check manually, (that is checking condition and executing line by line) the value of the function converged to zero in 5 iterations and the value of 'x' also was correct. But when I run the program as whole while doesnt start at all. I dont get any error message either. I am unable to find the mistake. Checked some answers from matlab forum , I am not getting matched solutions.
% The value of the function goes to zero at x = 0.8660
clearvars;clc
f = @(x) 4*x^2 - 3;
h = 0.0001;
x(1) = 0.5;
y(1) = f(x(1));
i = 1;
while (abs(y(i)) < 1e-4)
fprintf('value of current y: %d\n',(y(i))) % to check of loop enters
% just takes the next value of x
x(i+1) = x(i) - (f(x(i))/((f(x(i) + h) - f(x(i) - h))/((x(i)+h) - (x(i) - h))));
% function value at i+1
y(i+1) = f(x(i+1));
i=i+1;
end

Accepted Answer

Stephen23
Stephen23 on 22 Jan 2020
Lets have a look at the first y value:
>> f = @(x) 4*x^2 - 3;
>> x(1) = 0.5;
>> y(1) = f(x(1))
y = -2
And now look at your while loop condition:
i = 1;
while (abs(y(i)) < 1e-4)
Do you expect 2 to be less than 0.0001 ?
  1 Comment
Karthi Ramachandran
Karthi Ramachandran on 23 Jan 2020
My bad.. mind was off may be ... thank you very much for pointing my silly mistake

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!