![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/572707/image.png)
my newton code is not working for fing root of f = 2.5- 1/x
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 ?
0 comentarios
Respuestas (1)
DGM
el 4 de Abr. de 2021
Editada: DGM
el 4 de Abr. de 2021
Well, it is working, but you're operating near a singularity with particularly problematic symmetry.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/572707/image.png)
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 comentarios
DGM
el 5 de Abr. de 2021
Editada: DGM
el 5 de Abr. de 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.
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!