My preferred way to approximate a derivative is the central difference, its more accurate than forward difference or backward difference, and I'm too lazy to go higher-order. But the central difference requires a data point on either side of point you are evaluating. Normally this means you end up not having a derivative at either endpoint. To solve it, I want you to switch to forward and backward difference at the edges:
Specifically, I want you to use a forward difference for the first point, a backward difference for the last point, and a central difference for all the points in the middle. Also, you can assume x values are evenly spaced, and focus only on y. Use these formulas:
Good luck, I'm looking forward to seeing if someone comes up with a simple rule which reproduces all 3 derivatives in the right places!
EX INPUT:
0.034 9.62 8.885 3.477 2.38
I will use FD, CD, and BD to denote which algorithm to use in which spot, so above 5 points are used to approximate derivatives using
FD CD CD CD BD
And then the calculated values would be:
9.586 4.4255 -3.0715 -3.2525 -1.097
You can assume that there will always be at least 3 input points, and you can calculate using single or double precision.
And as always, shortest answer wins.
[a,b,c,d,e] -> [b-a,(c-a)/2,(d-b)/2,(e-c)/2,e-d]
. Can there be fewer that 3 input points? \$\endgroup\$