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 f'(x) = \lim_{dx \to 0} \frac{f(x+dx)-f(x)}{dx}. 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))
> (define (cube x) (* x x x))
> ((deriv cube) 2)
> ((deriv cube) 3)
> ((deriv cube) 4)

Those results are reasonably close to the actual derivative of 3x^2. 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.

Pages: 1 2