0

I am trying to add bounds to the code but having troubling figuring out where to put them. The equation goes: f(x) = e^(6x) + 1.441e^(2x) − 2.079e^(4x) − 0.333 = 0, -1>=x<=0

function c = newton(x0, delta)

c = x0;    
fc = f(x0);                   
fprintf('initial guess:  c=%d, fc=%d\n',c,fc)

if abs(fc) <= delta             % check to see if initial guess satisfies
      return;                       % convergence criterion.
end;

while abs(fc) > delta,
  fpc = fprime(c);        

  if fpc==0,                    % if fprime is 0, abort.
    error('fprime is 0')        % the error function prints message and exits
  end;

  c = c - fc/fpc;               % Newton step
  fc = f(c);
  fprintf('   c=%d, fc=%d\n',c,fc)
end;

function fx = f(x)
    fx = exp(6*x)+1.441*exp(2*x)-2.079*exp(4*x)-0.333;         % Enter your function here.
    return;
function fprimex = fprime(x)
    fprimex = 6*exp(6*x)+6*exp(2*x)*(ln(2))^2-4*exp(4*x)*ln(8); % Enter the derivative of function

    return;
Stan-Lee
  • 11
  • 5

1 Answers1

0

I would add the check after the Newton step. This won't protect against someone entering a -1 or 1 as an initial guess, but that could be done when you do your input validation. I took Ander Biguri's advice and changed the c to x:

function x = newton(x0, delta)
  x = x0;    
  fx = f(x0);                   
  fprintf('initial guess:  x=%f, fx=%f\n',x,fx)

  if abs(fx) <= delta             % check to see if initial guess satisfies
        return;                       % convergence criterion.
  end;

  while abs(fx) > delta,
    fpx = fprime(x);

    if fpx==0,                    % if fprime is 0, abort.
      error('fprime is 0')        % the error function prints message and exits
    end;

    x = x - fx/fpx;               % Newton step
    if( x > 1 || x < -1 )
      error('x out of bounds!');
    end

    fx = f(x);
    fprintf('   x=%f, fx=%f\n',x,fx)
  end
end

function fx = f(x)
  fx = exp(6*x)+1.441*exp(2*x)-2.079*exp(4*x)-0.333;         % Enter your function here.
end

function fprimex = fprime(x)
  fprimex = 6*exp(6*x)+6*exp(2*x)*(log(2))^2-4*exp(4*x)*log(8); % Enter the derivative of function
end

Here's the output I get:

>> x = newton(0.5, 0.5*1e-4)
initial guess:  x=0.500000, fx=8.307733
   x=0.375798, fx=2.908518
   x=0.263566, fx=1.003444
   x=0.165026, fx=0.340291
   x=0.081315, fx=0.113210
   x=0.012704, fx=0.036909
   x=-0.041514, fx=0.011793
   x=-0.082894, fx=0.003695
   x=-0.113515, fx=0.001136
   x=-0.135581, fx=0.000341
   x=-0.151084, fx=0.000098
   x=-0.161526, fx=0.000025

x =

   -0.1615
rayryeng
  • 102,964
  • 22
  • 184
  • 193
macduff
  • 4,655
  • 18
  • 29
  • 1
    Ander's advice :P Good job. – Ander Biguri Oct 12 '15 at 16:18
  • Thanks! What are you entering in the command window to get the output, for some reason when I am inserting initila point and whatnot, I keep getting an error. Maybe I am typing it in wrong. – Stan-Lee Oct 12 '15 at 16:23