Skip to content

Instantly share code, notes, and snippets.

@zallarak
Created January 14, 2012 23:12
Show Gist options
  • Save zallarak/1613306 to your computer and use it in GitHub Desktop.
Save zallarak/1613306 to your computer and use it in GitHub Desktop.
Symbolic differentiation
; Symbolic differentiation
(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0))
((sum? exp)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
((product? exp)
(make-sum
(make-product (multiplier exp)
(deriv (multiplicand exp) var))
(make-product (deriv (multiplier exp) var)
(multiplicand exp))))
(else
(error "unkown expression type"))))
; The above code is a conditional structure for
; representing how to take derivatives recursively
; Above function has undefined items
; they shall be defined below:
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2)))
(define (make-sum a1 a2) (list '+ a1 a2))
(define (make-product m1 m2) (list '* m1 m2))
(define (sum? x)
(and (pair? x) (eq? (car x) '+)))
(define (addend s) (cadr s))
(define (augend s) (caddr s))
(define (product? z)
(and (pair? z) (eq? (car z) '*)))
(define (multiplier p) (cadr p))
(define (multiplicand p) (caddr p))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment