Numerical derivatives in Scilab

I’ll try to explain it a little bit easier than in the Scilab’s Help.

Suppose, you have a function of one variable, e.g.

y = x2


function y=f(x)
    y=x^2
endfunction

To take its derivative, write another function


function y=df(x)
    y=numderivative(f,x)
endfunction

Now, if you want to plot this derivative, you need to compute its values at a number of points, that are usually equally spaced.

You can do it like this:


x=linspace(0,10,20)';
y=feval(x,df);

plot(x,y,'x')

If your function depends on other parameters, say,

y = p1 sin (p2x)

then the code for calculating and plotting its derivative is:


function y=f(x, p1,p2)
  y = p1*sin(x*p2)
endfunction

function y=df(x)
    y=numderivative(list(f, p1,p2), x)
endfunction

p1 = 2;
p2 = 3;
x=linspace(0,2*%pi,200)';
y=feval(x,df);

plot(x,y,'x')

Higher order derivatives can be obtained by applying numderivative repeatedly:


function y=f(x)
    y=sin(x)
endfunction

function y=df(x)
    y=numderivative(f,x)
endfunction

function y=d2f(x)
    y=numderivative(df,x)
endfunction

x=linspace(0,2*%pi,200)';
y=feval(x,d2f);

plot(x,y,'x')

It’s possible to use a for loop to get the n-th derivative of a function f for an arbitrary n


old = 'f';
for i=1:n
    new = 'd'+string(i)+'f';
    deff('y='+new+'(x)','y=numderivative('+old+',x)');
    old=new;
end

x=linspace(0,2*%pi,200)';
execstr('y=feval(x,'+new+');');

But be careful! Numerical errors increase with the number of iterations.

This is what happens, for example, to the derivatives of the function y=x4

Der 02

Looks good

***

Der 03

Worse, but still acceptable

***

Der 04

Totally messed up

This is common: while integrals are easier calculated numerically than analytically, the situation with derivatives is opposite. They are easier treated analytically than numerically.

Advertisements
Published in: on 02/08/2015 at 02:55  Leave a Comment  

The URI to TrackBack this entry is: https://burubaxair.wordpress.com/2015/08/02/numerical-derivatives-in-scilab/trackback/

RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: