%Example of taking a derivative with an algorithm
clear;
f=@(x) x^3; %we need @(x) to tell MATLAB x is the variable
g=@(x) 3*x^2; %* is times
N=input('Type a number where you want to evaluate the derivative of x^3\n')
disp('The actual values is:')
g(N)
%We try to approximate f'(x) with (f(x+h)-f(x-h))/2h
h=0.1; %we first try with this h
D=(f(N+h)-f(N-h))/(2*h);
%We try to stay close at least 0.05
while abs(D-g(N))>0.05 %abs is the absolute value, a function in MATLAB
    h=h/2;
    D=(f(N+h)-f(N-h))/(2*h);
end
disp('The approximation we got is:')
D
%Since in general we do not know f', we cannot compare the approximation
%with the real value. For this reason, we decide to stop when two
%successive approximations are very close
k=0.5;
E=(f(N+k)-f(N-k))/(2*k);
F=(f(N+(k/2))-f(N-(k/2)))/(k);
%We decide to stop when two successive approximation are not
%further than 0.1
while abs(E-F)>0.1
    k=k/2;
    E=F;
    F=(f(N+(k/2))-f(N-(k/2)))/(k);
end
disp('The approximation we got this way is:')
E
