Reputation: 23
So I am meant to write a Matlab function that has a starting guess p and tolerance e as inputs and outputs the number of iterations n and final fixed point approx pn satisfying abs(pn-pn-1) <= e for a given function g. Here is what I currently have:
function f = fixed(p,e)
i=1;
pn=g(p);
while (abs(pn - p) <= e)
pn = g(p)
i=i+1;
p=pn
end
end
But I'm not sure where I'm going wrong. Do I need to include another if statement in the case that the absolute difference is >e? What else would I include in such a statement?
Upvotes: 1
Views: 308
Reputation: 29244
Try this:
function f = fixed(p,e)
i=1;
pn=g(p);
while (abs(pn - p) <= e)
p = pn
pn=g(p)
i=i+1;
end
f = pn
end
I think you were comparing p
and pn
after the p=pn
statement causing an early exit.
Upvotes: 1