1

I have created a program in Matlab to try to find the root of f(x) = exp(2x) + 3x - 4 (the function "fopg1" in my code). My code is as follows:

format long
tic;
for dum=1:1000;
    x(1) = 0.5;
    x(2) = 0.4;
    err_tol = 1e-8;
    iteration(1) = 1;
    n = 3;
    while err_estimate > err_tol
        iteration(n) = n;
        x(n) = x(n-1) - fopg1(x(n-2)) * ((x(n-1) - x(n-2)) / (fopg1(x(n-1)) - fopg1(x(n-2))));
        err_estimate(n) = abs(x(n) - x(n-1));
        n = n + 1;
    end
%end
time = toc;
avgtime = time/1000;
A = [iteration' x' err_estimate' tbd'];
f = '%2i %13.9f %13.9f %7.3f'; compose(f,A)

Unfortunately this does not converge. I feel like it should. Is there a flaw in my program or does it in fact not converge? Thanks in advance.

Maarten

p.late
  • 31
  • 6
  • well, there must be some `x` with `f(x) = 0`, as `f(x)` is continuous (composition of continuous functions), `f(0) = -3` and `f(1) > 0`. So it seems there is a logical error in your function. – EagleRainbow Feb 24 '18 at 21:02
  • 1
    dum is a for loop to get an average tic toc time over 1000 iterations. one end is missing, I will fix that – p.late Feb 24 '18 at 21:47
  • That is the point. To measure average computing time, since matlab computing time can sometimes differ. – p.late Feb 25 '18 at 11:10

1 Answers1

0

I answered a very similar question here a few days ago. Using the same code, without an iterations limit and with an increased tolerance (1e-8 as per your example), I detect the expected convergence of exp(2x) + 3x - 4 using the secant method:

clear();
clc();

com = Inf;
i = 2;
err_tol = 1e-8;

f = @(x) exp(2*x) + 3*x - 4;

x(1) = 0.5;
x(2) = 0.4;

while (abs(com) > err_tol)
    com = f(x(i)) * (x(i) - x(i-1)) / (f(x(i)) - f(x(i-1)));
    x(i+1)= x(i) - com;

    i = i + 1;
    n = n - 1;
end

display(['Root X = ' num2str(x(end))]);

The message I receive is: Root X = 0.47369. It shouldn't be hard for you to implement your additional data within this code.

Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
  • Thanks a lot, I will look at this today. The 1000 iterations are used to measure average time and do not have any effect on the Secant method itself. – p.late Feb 25 '18 at 11:09