Isoraqathedh

d/dx I

Aug 2nd, 2014
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lisp 1.64 KB | None | 0 0
  1. (defun d/dx (expr)
  2.   "Derives expr with respect to x"
  3.   (cond ((consp expr)
  4.          (destructuring-bind (key &rest args) expr
  5.            (case key
  6.              (+ (cons '+ (loop for i in args collect (d/dx i))))
  7.              (* (independent-factors args))
  8.              (expt
  9.               (destructuring-bind (base expt &aux (base-x-p (eql base :x)) (expt-x-p (eql expt :x))) args
  10.                 (cond ((and base-x-p expt-x-p) '(* (expt :x :x) (1+ (log :x))))
  11.                       ((and base-x-p (not expt-x-p)) (power-law args))
  12.                       ((and (not base-x-p) expt-x-p) (rule-of-exponents args))
  13.                       (t (cons 'expt args))))))))
  14.         ((eql expr :x) 1)
  15.         (t 0)))
  16.  
  17. (defun power-law (list)
  18.   "Derives (x^n) into (nx^(n − 1))"
  19.   (destructuring-bind (base expt) list
  20.     (cond ((equal expt 2) `(* 2 ,base))
  21.           ((equal expt 1) 1)
  22.           ((numberp expt) `(* ,expt (expt ,base ,(1- expt))))
  23.           (t `(* ,expt (expt ,base (1- ,expt)))))))
  24.  
  25. (defun rule-of-exponents (list)
  26.   "Derives (n^x) into (n^x ln n)"
  27.   (destructuring-bind (base expt) list
  28.     (if (eql base :e)
  29.         (cons 'expt list)
  30.         `(* (expt ,base ,expt) (log ,base)))))
  31.  
  32. (defun constant-rule (number)
  33.   (declare (ignore number))
  34.   "All constants become zero."
  35.   0)
  36.  
  37. (defun independent-factors (list-of-multiplicands)
  38.   "All constant multipliers can be left alone."
  39.   (cons '* (loop for i in  list-of-multiplicands
  40.                  collect (cond ((numberp i) i)
  41.                                ((and (listp i)
  42.                                      (eql (car i) 'expt)) (d/dx i))
  43.                                (t 1)))))
Advertisement
Add Comment
Please, Sign In to add comment