Calculating Derivatives
May 5, 2017
I’ve seen this before, and when I ran across it again a few days ago decided to share it with all of you. This is why I like Scheme so much:
In mathematics, the derivative of a function f(x) is . Here’s a simple implementation in Scheme, with an example:
Petite Chez Scheme Version 8.4 Copyright (c) 1985-2011 Cadence Research Systems > (define dx 0.0000001) > (define (deriv f) (define (f-prime x) (/ (- (f (+ x dx)) (f x)) dx)) f-prime) > (define (cube x) (* x x x)) > ((deriv cube) 2) 12.000000584322379 > ((deriv cube) 3) 27.000000848431682 > ((deriv cube) 4) 48.00000141358396
Those results are reasonably close to the actual derivative of . The code is identical to the math.
Your task is to write a function to calculate derivatives in your favorite language. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution in the comments below.