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)