Double Derivatives and Beyond

So I've actually gone through calc classes A through C, but it occured to me that I have done nothing with this knowledge.
I decided to implement some common theorems into functions, but I ran into a snag so soon that it's annoying me.
I tried to implement an approximation function for derivative and second derivative using the definition of a derivative. I've tested it's accuracy with sin/cos as it's inputs.
The first order derivative has pretty good accuracy, achieving about 10-11 digits before going off (not bad but not great, probably eroneous getting that good since h itself is not that small).
Second order gets worse much quicker, and no matter the amount of tweaking I do to 'h' I can't get it better. I've looked at LDBL_EPSILON on my computer and it shows a number that should initially be accurate something like 1.08e-19, so why can't I get 'h' lower?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <cfloat>

/* unfortunately, while this is using the definition of
 * a derivative to achieve an aproximation of the derivative,
 * owing to limitations to the hardware this ultimately ends
 * up with quite a large error margin...
 * perhaps by using assembly this margin could be reduced, but I'm
 * not ready to go this far.
 */

using namespace std;

const long double h = 0.0000008;



long double derive(long double val, long double(*funct)(long double))
{

	return ((funct(val+h)-funct(val-h))/(2*h));
}

long double d_derive(long double val, long double (*orig)(long double) )
{

	return (derive(val+h, orig) - derive(val - h, orig))/(2*h); 
}	 



P.S. my compiler or hardware appears to set long double to the same size as double, so you may get better results with an 80 bit floating number.
I've tried setting h to multiples of DBL_EPSILON (both by squares of twos and by tens, and haven't gotten better than the above setting of h)
Last edited on
Where's main?
You are using the first derivative to get the second. This sounds good, but if you actually track the main function evaluations you will find that you are decoupling the odd and even positions ("checkerboard problem"). You are also effectively doubling the step size (so quadrupling the error for a second-order method).

A better approximation for the second derivative is
(funct(val+h)-2*funct(val)+funct(val-h))/h^2

If you expand with Taylor's Theorem you can show it is second-order accurate. It's also the standard discretisation in the diffusion equation, if you want to google that.
Last edited on
Topic archived. No new replies allowed.