% This is a demo to show how to use the symbolic pkg. to
% calculate the derivative of an Anonymous function and then
% use the results in normal octave programming. 

% this is just a formula to start with
% have fun and change it if you want to.
f=@(x) x.^2 +3*x-1 + 5*x.*sin(x);




function NRdemo(f, guess, rlow,rhi)
%% The symbolic pkg must be loaded 
%% f is the input Anonymous function to find the roots of.
%% guess is the initial guess
%% It should be close to the root you are looking for.
%% rlow is the low end of the range for plotting
%% rhi is the high end of the range for plotting

f  % this displays the original function

% the next 2 line take the Anonymous function into a symbolic formula
syms x;
ff=formula(f(x));
% now calculate the derivative of the function 
ffd=diff(ff);
% and convert it back to an Anonymous function
df=function_handle(ffd)

% now we plot the function and its derivative
rs=(rhi-rlow)/10000;
x1=rlow:rs:rhi;
y=f(x1);
y2=df(x1);
plot(x1,y,x1,y2)
legend ("f","f '");
hold on
plot(guess,0,'rx') % plot each guess
grid minor on
% now use Newton-Raphston method to find the roots
finished=false;
h=guess
 plot([h h],[0 f(h)],'r')
while(~finished)
 hn=h-f(h)/df(h) % this is guess - f/f'
 if(abs(h-hn)<1e-6) % check to see if we are done
  finished=true;
 endif

 plot(hn,0,'rx') % plot each guess
 plot([hn h] ,[0 f(h)], 'r') # and the slopes
 plot([hn hn],[0 f(hn)],'r')
  h=hn;
endwhile

plot(h,0,'o') % plot the answer.
grid on
hold off
endfunction


# start of main program
figure(1) 
x1=-10:.1:10;
plot(x1,f(x1))
grid minor on

guess=input("Please enter a starting value near a zero crossing.")

figure(2)
% finaly this is the call to the function
NRdemo(f,guess,-15,10)
