Function: math-nlfit-least-squares

math-nlfit-least-squares is a byte-compiled function defined in calc-nlfit.el.gz.

Signature

(math-nlfit-least-squares XDATA YDATA &optional SDATA SIGMAS)

Documentation

Return the parameters A and B for the best least squares fit y=a+bx.

Source Code

;; Defined in /usr/src/emacs/lisp/calc/calc-nlfit.el.gz
(defun math-nlfit-least-squares (xdata ydata &optional sdata sigmas)
  "Return the parameters A and B for the best least squares fit y=a+bx."
  (let* ((n (length xdata))
         (s2data (if sdata
                     (mapcar 'calcFunc-sqr sdata)
                  (make-list n 1)))
         (S (if sdata 0 n))
         (Sx 0)
         (Sy 0)
         (Sxx 0)
         (Sxy 0)
         D)
    (while xdata
      (let ((x (car xdata))
            (y (car ydata))
            (s (car s2data)))
        (setq Sx  (math-add Sx (if s (math-div x s) x)))
        (setq Sy  (math-add Sy (if s (math-div y s) y)))
        (setq Sxx (math-add Sxx (if s (math-div (math-mul x x) s)
                                  (math-mul x x))))
        (setq Sxy (math-add Sxy (if s (math-div (math-mul x y) s)
                                  (math-mul x y))))
        (if sdata
            (setq S (math-add S (math-div 1 s)))))
      (setq xdata (cdr xdata))
      (setq ydata (cdr ydata))
      (setq s2data (cdr s2data)))
    (setq D (math-sub (math-mul S Sxx) (math-mul Sx Sx)))
    (let ((A (math-div (math-sub (math-mul Sxx Sy) (math-mul Sx Sxy)) D))
          (B (math-div (math-sub (math-mul S Sxy) (math-mul Sx Sy)) D)))
      (if sigmas
          (let ((C11 (math-div Sxx D))
                (C12 (math-neg (math-div Sx D)))
                (C22 (math-div S D)))
            (list (list 'sdev A (calcFunc-sqrt C11))
                  (list 'sdev B (calcFunc-sqrt C22))
                  (list 'vec
                        (list 'vec C11 C12)
                        (list 'vec C12 C22))))
        (list A B)))))