Talk:Arithmetic-geometric mean

From Wikipedia, the free encyclopedia

What is the arithmetic-geometric mean of 1 and 2? AxelBoldt

To answer this, I added a Scheme implementation of the algorithm. (agmean 1 2 .000000001) => 1.4567910310469068 -- Damian Yerrick

Here is an alternative implementation in Scheme that is conceptually similar but is simpler (I checked this in Guile and it works):

(define (agm a b epsilon)
  ;; Determine if two numbers are already very close together
  (define (ratio-diff a b) (abs (/ (- a b) b)))
  ;; Actually do the computation
  (define (loop a b)
    ;; If they're already really close together, just return the arithmetic mean
    (if (< (ratio-diff a b) epsilon)
        (/ (+ a b) 2)
        (loop (sqrt (* a b)) (/ (+ a b) 2)))) ; otherwise, do another step
  ;; Error checking
  (if (or (not (real? a))
          (not (real? b))
          (<= a 0)
          (<= b 0))
    (error 'agm "~s and ~s must both be positive real numbers" a b)
    (loop a b)))