I am trying to find out how many iterations it takes when I run a secant iteration up to a certain tolerance in maple. However, I am receiving an error code, so if someone could point out where the mistake is in my code, I would really appreciate it.
kind regards.
x0 = 1.22, x1 = 0.8843478306, tolerance 1*e-6 > abs(x1-x0) how many iterations before the tolerance is reached?
restart;
secant:=proc(f,x0,x1)
local k,x;
x[0]:=x0;
x[1]:=x1;
print(0,x[0]);
print(1,x[1]);
for k from 2 to 1e-6 > abs(x1-x0) do
x[k]:=x[k-1]-f(x[k-1])*(x[k-1]-x[k-2])/(f(x[k-1])-f(x[k-2]));
print(k,x[k]);
end do;
return x;
end proc;
f1:= x -> 3.0*exp(-1.0*x)-(4.1)*x^2;
y := secant(f1, 1.22, 0.8843478306)
Error, (in secant) final value in for loop must be numeric or character
I put your condition (testing againgst the tolerance) in a
whileconditional test. I also added a hard-coded upper value for thekloop index as20, so that it doesn't run away forever for an example that doesn't converge.Check it over to understand how/why it works, and whether I made any mistake(s).