[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Numerical differentiation, recursion of functions not working
From: |
Martin Helm |
Subject: |
Re: Numerical differentiation, recursion of functions not working |
Date: |
Mon, 29 Mar 2010 21:23:14 +0200 |
User-agent: |
KMail/1.12.4 (Linux/2.6.31.12-0.2-desktop; KDE/4.3.5; x86_64; ; ) |
Am Montag, 29. März 2010 20:56:05 schrieb Martin Helm:
> > > Stefan
>
> You can (just for fun) do some lisp like higher order function trickery,
> for example
>
> function df = deriv(f)
> df = @(x) (f(x+1e-5)-f(x-1e-5))/2e-5;
> endfunction
>
> df = deriv(@sin)
>
> => df =
> @(x) (f (x + 1e-5) - f (x - 1e-5)) / 2e-5
>
>
> d2f = deriv(df)
>
> => d2f =
> @(x) (f (x + 1e-5) - f (x - 1e-5)) / 2e-5
>
> This seems to look the same but is not :-)
>
> df(0)
> => 1.00000
>
> d2f(0)
> => 0
>
> as it should be!
>
> Think about it (the trick is I am using closures here by using anonymous
> functions - or more lispy: lambda expressions)
>
> - mh
>
Go even one step further and define
function dfh = df_h ( f, h)
dfh = @(x) (f (x+h) - f (x-h))/2/h;
endfunction
D = @(f) df_h (f, 1e-5) # partial evaluation to get fixed stepsize
=> D =
@(f) df_h (f, 1e-5)
d2sin = D(D(@sin))
=> d2sin =
@(x) (f (x + h) - f (x - h)) / 2 / h
d2sin ([0:0.2:pi])
ans =
0.00000 -0.19867 -0.38942 -0.56464 -0.71736 -0.84147 -0.93204
-0.98545 -0.99957 -0.97385 -0.90930 -0.80850 -0.67546 -0.51550 -0.33499
-0.14112
This works of course not only for builtin functions.
- mh