While loop not starting

1 回表示 (過去 30 日間)
Karthi Ramachandran
Karthi Ramachandran 2020 年 1 月 22 日
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

採用された回答

Stephen23
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 ?
  1 件のコメント
Karthi Ramachandran
Karthi Ramachandran 2020 年 1 月 23 日
My bad.. mind was off may be ... thank you very much for pointing my silly mistake

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by