Advertisement
Guest User

Lagrange Interpolation

a guest
Jan 10th, 2025
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lisp 1.16 KB | Source Code | 0 0
  1. (defun make-poly (xys)
  2.   (case (length xys)
  3.     (0 (error "must have some points."))
  4.     (1 (destructuring-bind ((x1 . y1)) xys
  5.        (declare (ignore x1))
  6.        (constantly y1)))
  7.     (2 (destructuring-bind ((x1 . y1)(x2 . y2)) xys
  8.        (lambda(x)
  9.          (+ (/ (* (- x x2) y1)
  10.            (- x1 x2))
  11.         (/ (* (- x x1) y2)
  12.            (- x2 x1))))))
  13.     (3 (destructuring-bind ((x1 . y1)
  14.                 (x2 . y2)
  15.                 (x3 . y3))
  16.        xys
  17.      (lambda(x)
  18.        (+ (/ (* (- x x2)(- x x3) y1)
  19.          (- x1 x2)(- x1 x3))
  20.           (/ (* (- x x1)(- x x3) y2)
  21.          (- x2 x1)(- x2 x3))
  22.           (/ (* (- x x1)(- x x2) y3)
  23.          (- x3 x1)(- x3 x2))))))
  24.     (otherwise (lambda(x)
  25.      (loop for (xi . yi) in xys
  26.            for i from 1
  27.            sum (* yi (fancy-product xi xys x i 1)))))))
  28.  
  29. (defun fancy-product (xi points x omit count)
  30.   ;; neutral element for multiplication is 1
  31.   (if (endp points) 1 ;all done
  32.       (if (= count omit)
  33.       ;; skip this one
  34.       (fancy-product xi (cdr points) x omit (+ count 1))
  35.       ;; do all the rest
  36.       (destructuring-bind ((xj . yj) . rest-of-points) points
  37.         (declare (ignore yj))
  38.         (* (/ (- x xj)(- xi xj))
  39.            (fancy-product xi rest-of-points x omit (+ count 1)))))))
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement