Azzera filtri
Azzera filtri

my newton code is not working for fing root of f = 2.5- 1/x

3 visualizzazioni (ultimi 30 giorni)
hi sir, this is my code, I am tring to use my newton code to find the root of f = 2.5 - 1/x but my error keeps = 1 and runs in to error
f = @(x) 2.5 - 1/x
df = @(x) x.^-2
error = 100
xi = 10
iter = 1
while error > 1
xii = xi - (f(xi)/df(xi))
error = ((xii-xi)/xii)*100
error = abs(error)
xi=xii
iter = iter+1
end
I knot the root is at 2.5 but how can I get it ?

Risposte (1)

DGM
DGM il 4 Apr 2021
Modificato: DGM il 4 Apr 2021
Well, it is working, but you're operating near a singularity with particularly problematic symmetry.
If you pick a large initial estimate, you're going to end up on the other side of the singularity, with the next step size being even larger. The solution will diverge away from the singularity location. Try a smaller initial estimate, something in the range of (0 0.8) (non-inclusive).
Alternatively, if you want to keep the solver from wandering into bad places, you can try something like this:
f = @(x) 2.5 - 1/x
df = @(x) x.^-2
error = 100
xi = 5 % normally this would cause the solver to diverge
constraint=[0 10]; % but keep the solution constrained
iter = 1
while error > 0.001
xii = xi - (f(xi)/df(xi));
xii = min(max(xii,constraint(1)+eps),constraint(2)-eps)
error = ((xii-xi)/xii)*100;
error = abs(error);
xi=xii;
iter = iter+1;
end
though bear in mind that a crude constraint like this might cause other problems in certain cases.
  4 Commenti
wenchong chen
wenchong chen il 4 Apr 2021
thank you very much! one more question, how can I keep guesing it until the error=0, find the number?
DGM
DGM il 5 Apr 2021
Modificato: DGM il 5 Apr 2021
I'm not sure what you're asking. I was going to say that the error will approach zero, but I see now that you're multiplying it by 100. I'm not sure why you're doing that.
f = @(x) 2.5 - 1/x
df = @(x) x.^-2
error = 1
xi = -5
constraint=[0 10];
iter = 1
while error > 1E-8 % we can pick whatever we want here
xii = xi - (f(xi)/df(xi));
xii = min(max(xii,constraint(1)+eps),constraint(2)-eps);
error = ((xii-xi)/xii);
error = abs(error);
xi=xii;
iter = iter+1;
end
fprintf('final error is %2.4e\n',error(end))
either way, the error can be made arbitrarily small. For this exit condition, it's 2E-9. For an exit condition of 1E-9, it's zero to within the datatype precision.
If you're asking something different, please clarify.

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by