While loop not starting
조회 수: 4 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
Stephen23
2020년 1월 22일
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 ?
추가 답변 (0개)
참고 항목
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!