Firstly, it makes sense to try to get the derivative of a pure function (which does not affect the external state and returns an accurate result for each input). Secondly, the type system of many programming languages ββincludes many step functions (for example, integers), which means that you will need to make your program work in terms of continuous functions in order to get a real first derivative. Thirdly, the derivation of any function is associated with its destruction and its symbolic manipulation. Thus, you cannot get a derivative of a function without knowing what operations it was performed with. This can be achieved with reflection.
You can create a derived approximation function if your programming language supports closures (i.e. nested functions and the ability to put functions in variables and return them). Here is an example JavaScript taken from http://en.wikipedia.org/wiki/Closure_%28computer_science%29 :
function derivative(f, dx) { return function(x) { return (f(x + dx) - f(x)) / dx; }; }
So you can say:
function f(x) { return x*x; } f_prime = derivative(f, 0.0001);
Here f_prime will approach function(x) {return 2*x;}
If a programming language implemented functions of a higher order and sufficient algebra, one could implement a real derivative function in it. It would be great.
source share