ODEs as Streams

I love Lisp!

But I cannot say I understand what characteristic of this language group I enjoy so much. Is it the parenthesis? Macro expansions? The cover of the wizard book? The bewilderment it causes C-programmers?

No, none of those things. Honestly, I am attracted to dialects of Lisp as vehicles for thought. This kind of metric that is difficult to quantify. Even qualitatively describing this quality is tough for me. But is not terribly difficult to show. Thus, the demonstration below: two equations one resonant and the other non-resonant.


;; Delay/force with memoization
(defmacro delay (x)
  `(let ((done nil) (val nil))
     (lambda ()
       (unless done (setf val ,x done t))
       val)))
(defun force (p) (funcall p))

;; Stream utilities
(defmacro cons-stream (a b) `(cons ,a (delay ,b)))
(defun stream-car (s) (car s))
(defun stream-cdr (s) (force (cdr s)))
(defun stream-ref (s n)
  (if (= n 0)
    (stream-car s)
    (stream-ref (stream-cdr s) (1- n))))

(defun step-stream (step f y0 dt)
  (labels ((gen (y tn)
                (cons-stream y
                             (gen (funcall step f tn y dt) (+ tn dt)))))
    (gen y0 0d0)))

(defun vadd (a b) (mapcar #'+ a b))
(defun vscale (k v) (mapcar (lambda (x) (* k x)) v))

;; The fourth-order Runge-Kutta method
(defun rk4 (f tn y dt)
  (let* ((h2 (/ dt 2))
         (k1 (funcall f tn y))
         (k2 (funcall f (+ tn h2) (vadd y (vscale h2 k1)))) 
         (k3 (funcall f (+ tn h2) (vadd y (vscale h2 k2))))
         (k4 (funcall f (+ tn dt) (vadd y (vscale dt k3)))))
    (vadd y (vscale (/ dt 6) (vadd (vadd k1 (vscale 2 k2)) (vadd (vscale 2 k3) k4))))))

;; Resonant system
(defun res (tn s)
  (declare (ignore tn))
  (list (- (first s)) (+ (* -2 (second s)) (expt (first s) 2))))
;; Non-resonant system
(defun non (tn s)
  (declare (ignore tn))
  (list (- (first s)) (+ (* -3 (second s)) (expt (first s) 2))))

;; y/x^2 at time tt, starting from (0.5,0)
(defun yx2 (f tt)
  (let ((s (stream-ref (step-stream #'rk4 f (list 0.5d0 0d0) 0.01d0)
                       (round (/ tt 0.01d0)))))
    (/ (second s) (expt (first s) 2))))

(format t "~6a ~12a ~12a~%" "t" "resonant" "non-resonant")
(dolist (tt '(0d0 2d0 4d0 6d0 8d0 10d0))
  (format t "~6,1f ~12,5f ~12,5f~%" tt (yx2 #'res tt) (yx2 #'non tt)))

When I run with sbcl via sbcl --script resonance.lisp, I get the following:

t      resonant     non-resonant
   0.0      0.00000      0.00000
   2.0      2.00000      0.86466
   4.0      4.00000      0.98168
   6.0      6.00000      0.99752
   8.0      8.00000      0.99966
  10.0     10.00000      0.99995