3

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

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
T.Omalley
  • 325
  • 1
  • 2
  • 9

1 Answers1

0

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]
acer
  • 6,671
  • 15
  • 15
  • Thanks once again Acer, this is the second time you have helped me out and I really appreciate it. Looking at my code and yours I have made a few syntax errors as well as using a different return function.. thank you very much. – T.Omalley Oct 26 '20 at 10:46
  • You're very welcome. I could also add that the conditional test was changed to use `abs(x[k-1]-x[k-2])` rather than `abs(x1-x0)`, so that the test would utilize the running values rather than be hard-coded with the input values. – acer Oct 26 '20 at 18:50
  • Yes, I noticed that one too but didn't quite understand why you had changed it, but that makes a lot of sense. Thank you so much – T.Omalley Oct 27 '20 at 19:34