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 while
conditional test. I also added a hard-coded upper value for the k
loop index as 20
, 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).
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 20 while abs(x[k-1]-x[k-2]) > 1e-6 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],abs(x[k]-x[k-1]));
end do;
return convert(x,list);
end proc:
f1:= x -> 3.0*exp(-1.0*x)-(4.1)*x^2:
secant(f1, 1.22, 0.8843478306);
0, 1.22
1, 0.8843478306
2, 0.6810954056, 0.2032524250
3, 0.6318451478, 0.0492502578
4, 0.6257917558, 0.0060533920
5, 0.6256275429, 0.0001642129
-7
6, 0.6256270427, 5.002 10
[1.22, 0.8843478306, 0.6810954056, 0.6318451478,
0.6257917558, 0.6256275429, 0.6256270427]