function df = dfunc(x,a)
% df = exp(x);
  df = sech(x)^2 + a;
function f = func(x,a,b)
%  f = exp(x) -2;
   f = tanh(x) + a*x + b;
clc; close all; clear all; format long e
fname = 'func';
fpname='dfunc';
delta = .0001;
 a = input('Enter a value:');
 b = input('Enter b value:');
x0 = linspace(-10,10,201);
y0 = feval(fname,x0,a,b);
xc = input('Enter starting value:');
 fc = feval(fname,xc,a,b);
%fpc=feval(fpname,xc,a,b);
fpc = (feval(fname,xc+delta,a,b)-fc)/delta;
k=0; disp(sprintf('k        x        fval          fpval   '))
while input('Newton step? (0=no, 1=yes)')
    k=k+1;
  x(k) = xc; y(k) = fc;
  xnew = xc - fc/fpc;
  xc   = xnew;
  fc = feval(fname,xc,a,b);
 %fpc= feval(fpname,xc,a);
  fpc = (feval(fname,xc+delta,a,b)-fc)/delta;
  disp(sprintf('%2.0f    %20.15f %20.15f    %20.15f',k,xc,fc,fpc))
end
  if x(1) <= x(k)
      xa = floor(x(1)-.5); xb = ceil(x(k)+.5);
  else
      xb = floor(x(1)-.5); xa = ceil(x(k)+.5);
  end     
x0 = linspace(xa,xb,201);
y0 = feval(fname,x0,a,b);
plot(x0,y0,x,y,'*')
% script SEC.M: uses secant method to find zero
% of user definred function in FUNC.M
close all;clear all; clc; format long e
fname = 'func';
a = input('Enter a:');b = input('Enter b:');
x0 = linspace(-10,10,201);
y0 = feval(fname,x0,a,b);
xc = input('Enter starting value:');
fc = feval(fname,xc,a,b);
delta = .0001;
fpc = (feval(fname,xc+delta,a,b)-fc)/delta;
k=0; disp(sprintf('k       x        fval       fpval   '))
while input('secant step? (0=no, 1=yes)')
    k=k+1;
 x(k) = xc; y(k) = fc;
  f_ = fc;
  xnew = xc - fc/fpc;
  x_   = xc;
  xc   = xnew;
  fc = feval(fname,xc,a,b);
  fpc= (fc - f_)/(xc-x_);
  disp(sprintf('%2.0f    %20.15f %20.15f    %20.15f',k,xc,fc,fpc))
end
 if x(1) <= x(k)
      xa = floor(x(1)-.5); xb = ceil(x(k)+.5);
  else
      xb = floor(x(1)-.5); xa = ceil(x(k)+.5);
  end     
  x0 = linspace(xa,xb,201); y0 = feval(fname,x0,a,b);
plot(x0,y0,x,y,'r*')
function x = sqrt1(A)
% A>= 0, x>= 0
if A < 0 break;end
if A == 0
 x = 0;
else
 TwoPower = 1;
 m = A;
 while m >=  1, m = m/4; TwoPower = 2*TwoPower  ; end
 while m < .25, m = m*4; TwoPower =   TwoPower/2; end
 % sqrt(A) = sqrt(m)*TwoPower
 x = (1+2*m)/3;
 for k = 1:4
     x = (x+ (m/x))/2;
 end
 x = x*TwoPower;
end
% script zeroin
% uses matlab builtin rootfinder "FZERO"
% to find a zero of a function 'fname'
close all; clear all; format long
%fname = 'func'; % user defined function-can also give as @func
%fpname='dfunc'; % user defined derivative-not required by FZERO
%disp(sprintf('k       fval       fpval   '))
delta = .0001; % function value limiting tolerance
 a = input('Enter a value:'); % parameter values for 'func'
 b = input('Enter b value:');
x0 = linspace(-10,10,201); y0 = feval(@func,x0,a,b);
xc = input('Enter starting value:');
%root = fzero(@func,xc,.0001,1,a,b); % grandfathered format
OPTIONS = optimset('MaxIter',100,'TolFun',delta,'TolX',delta^2);
root = fzero(@func,xc,OPTIONS,a,b)
y = feval(@func,root,a,b)
plot(x0,y0,root,y,'r*')

