While loop not starting

1 visualizzazione (ultimi 30 giorni)
Karthi Ramachandran
Karthi Ramachandran il 22 Gen 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

Risposta accettata

Stephen23
Stephen23 il 22 Gen 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 Commento
Karthi Ramachandran
Karthi Ramachandran il 23 Gen 2020
My bad.. mind was off may be ... thank you very much for pointing my silly mistake

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Programming in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by