I wrote a derivative function as follows:
(define (der f h)
(lambda (x)
(/ (- (f(+ x h)) (f x)) h)))
and another function for finding second and third derivatives :
(define (der-multiple f h n)
(if (= 0 n)
0
(der (f h)))
(- n 1))
I tried to plot the derivative of sin(x) as follows, but it did not work.
(define (f x) (der (sin x) 0.5))
(require plot)
(plot (function f (- 5) 5 #:label "sine^-1(x)")
#:x-min -5 #:x-max 5 #:y-min -5 #:y-max 5)
lang racket is imported, but all I am getting is a white screen. Did I do something wrong here? Should I change (lambda (x)) within the derivative function to something else to make the function easier to plot?
Updated Code
(define (der f h)
(lambda (x)
(/ (- (f(+ x h)) (f x))
h)))
(define (der-multiple f h n)
(if (= 0 n)
f
(der-multiple (der f h) h (- n 1))))
(define (der-sin-fourth h)
(der-multiple sin h 4))
(plot (function (der-sin-fourth 0.5) (- 5) 5 #:label "sine^-4(x)")
:x-min -5 #:x-max 5 #:y-min -5 #:y-max 5)
Your der
returns a function of x
, which is fine. But your
(define (f x) (der (sin x) 0.5))
has a number of problems. First, since der
returns a function, all that f
does is return a function - it does no computation on x
. Probably you wanted:
(define f (der (sin x) 0.5))
so that f
is actually bound to a function of x
.
Second, the argument to der
is expected to be a function, but with (sin x)
you, at best, pass in a number.
In summary, probably you want something like:
(define f (der sin 0.5))
Note, your h
of 0.5 is probably too big to get a reasonable derivative (recall sin
is periodic outside of {0, 2pi}). You'll have no issues making h
very small. Of course, when you plot it you can step x
by 0.5 if you want.
Your der-multiple
function isn't correct in a number of ways. Here is the proper version:
(define (der-n f h n)
(if (zero? n)
f
(der-n (der f h) h (- n 1))))