derive.lisp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. ;;;; derive.lisp
  2. ;;;;
  3. ;;;; Copyright (c) 2015 Samuel W. Flint <swflint@flintfam.org>
  4. (defpackage #:derive
  5. (:use #:cl)
  6. (:export :derive))
  7. (in-package #:derive)
  8. ;;; "derive" goes here.
  9. (defun derive (equation)
  10. "derive -- (derive equation)
  11. Derives an equation using the normal rules of differentiation."
  12. (declare (cons equation))
  13. (let ((op (first equation)))
  14. (cond
  15. ((member op '(sin cos tan csc sec cot sqrt))
  16. (chain equation))
  17. ((equal op 'expt)
  18. (power (rest equation)))
  19. ((equal op '*)
  20. (mult (rest equation)))
  21. ((equal op '/)
  22. (div (rest equation)))
  23. ((or (equal op '+)
  24. (equal op '-))
  25. (apply #'plus/minus op (rest equation)))
  26. ((numberp op)
  27. 0)
  28. (t
  29. 1))))
  30. (defun plus/minus (op &rest args)
  31. "plus/minus -- (plus/minus op &rest args)
  32. Derive for plus/minus"
  33. (declare (symbol op)
  34. (cons args))
  35. (let ((out (list op)))
  36. (loop for arg in args
  37. do (let ((derivative (derive (if (not (listp arg)) (list arg) arg))))
  38. (if (eq 0 derivative)
  39. nil
  40. (push derivative out))))
  41. (if (equal (list op) out)
  42. nil
  43. (reverse out))))
  44. (defun mult (equation)
  45. "mult -- (mult equation)
  46. Derive multiplication"
  47. (if (= (length equation) 2)
  48. (if (numberp (first equation))
  49. `(* ,(first equation) ,(derive (if (not (listp (second equation))) (list (second equation)) (second equation))))
  50. (if (numberp (second equation))
  51. `(* ,(second equation) ,(derive (if (not (listp (first equation))) (list (first equation)) (first equation))))
  52. `(+ (* ,(first equation) ,(derive (second equation)))
  53. (* ,(second equation) ,(derive (first equation))))))
  54. (mult (list (first equation) (mult (rest equation))))))
  55. (defun div (equation)
  56. "div -- (div equation)
  57. Derive using quotient rule"
  58. (let ((numerator (nth 0 equation))
  59. (denominator (nth 1 equation)))
  60. `(/ (- (* ,numerator ,(derive denominator))
  61. (* ,denominator ,(derive numerator)))
  62. (expt ,denominator 2))))
  63. (defun chain (equation)
  64. "chain -- (chain equation)
  65. Apply the chain rule to the equation"
  66. (declare (cons equation))
  67. )
  68. (defun power (eq)
  69. "power -- (power rest)
  70. Apply the Power Rule"
  71. (declare (cons eq))
  72. (let ((equation (nth 0 eq))
  73. (power (nth 1 eq)))
  74. (if (listp equation)
  75. `(* ,power (expt ,(derive equation) ,(1- power)))
  76. `(* ,power (expt ,equation ,(1- power))))))
  77. ;;; End derive