I can't seem to make the correct outcome, but I don't know how to set up my nth value any way else... It does the 0th and 1st derivative correctly then it gives me a crazy negative number.. do you know what could be the problem?
Code:
(define (der f h)
(lambda (x) (/ (- (f (+ x h)) (f x))
h)
)
)
(define (cube x) (* x x x))
(define (many-der f h n)
(if (= n 0)
f
(many-der (der f h) h (- n 1))))
(define der-of-cube-n (many-der cube .00000000000001 2))
(der-of-cube-n 5)
-142108547152020.03
I've attempted to rearange it so then the else statement starts with der but I get the same output when n=2...
Any help would be greatly appreciated!!
Your h
of .00000000000001
is too small; so small that you are running into rounding errors. Here is a result with another h
(define der-of-cube-n (der-n cube 0.0001 2))
> (der-of-cube-n 5)
30.000597917023697
Note: second derivative of x^3
is 6x
.
Of course, one of the important attributes of Scheme is that it supports exact numbers of arbitrary precision. So if you really want h
to be that small you can formulate your inputs to be 'exact'. Like this:
> (define der-of-cube-n (der-n cube (/ 10000000000000) 2))
> (der-of-cube-n 5)
150000000000003/5000000000000
> (rationalize (der-of-cube-n 5) 0.01)
3e1