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

3 次查看(过去 30 天)
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 ?

回答(1 个)

DGM
DGM 2021-4-4
编辑:DGM 2021-4-4
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 个评论
wenchong chen
wenchong chen 2021-4-4
thank you very much! one more question, how can I keep guesing it until the error=0, find the number?
DGM
DGM 2021-4-5
编辑:DGM 2021-4-5
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by