While loop not starting
2 次查看(过去 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 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!