;23-Jun-1999                                                    Alain Brobecker
;Babylon algorithm's to approximate 2

;The original method is described using a rectangle of size L(0)=2 and l(0)=1
;and creating a new one with same area and length L(1)=(L(0)+l(0))/2, so:
;           L(0)=2
;           l(0)=1
;           L(n+1)=(L(n)+l(n))/2
;           l(n+1)=2/L(n+1) (=4/((L(n)+l(n)))
;Then we have l(0) < l(1) < .. < l(n) < 2 < L(n) < .. < L(1) < L(0),
;ie L(n) and l(n) are adjacents and tends toward 2.

;This convergence is very fast (quadratic CV), and this can be proven using
;Newton's method with L(n+1)=L(n)/2+1/L(n).

 10         ;number of iterations (future version will ask for precision)
 2 1        ;L(0)=2
 1 1        ;l(0)=1
.iter
 Q+         ;L(n)+l(n)
 2 *        ;L(n+1)=(L(n)+l(n))/2
 COPY2      ;L(n+1) L(n+1)
 2 *        ;L(n+1) L(n+1)/2
 SWAP2      ;L(n+1) l(n+1)=2/L(n+1)
 COPY2 QPRINT " < 2 < "
 QSWAP2     ;L(n+1) l(n+1)=2/L(n+1)
 COPY2 QPRINT CR
 QSWAP2
 5 SWAP
 1 - COPY SKIP<>0 END
 5 SWAP
 iter

#QSWAP2 3 SWAP SWAP2 4 SWAP SWAP2 END
#QPRINT SWAP2 HPRINT "/" HPRINT END

;IN         p1 q1 p2 q2
;OUT        p1*q2+p2*q1 q1*q2
#Q+
  COPY      ;p1 q1 p2 q2 q2
  4 SWAP    ;p1 q2 p2 q2 q1
  COPY      ;p1 q2 p2 q2 q1 q1
  3 SWAP    ;p1 q2 p2 q1 q1 q2
  *         ;p1 q2 p2 q1 q1*q2
  3 SWAP    ;p1 q2 q1*q2 q1 p2
  *         ;p1 q2 q1*q2 p2*q1
  SWAP2     ;p1 q2 p2*q1 q1*q2
  4 SWAP    ;q1*q2 q2 p2*q1 p1
  SWAP2     ;q1*q2 q2 p1 p2*q1
  3 SWAP    ;q1*q2 p2*q1 p1 q2
  *         ;q1*q2 p2*q1 p1*q2
  +         ;q1*q2 p1*q2+p2*q1
  SWAP2
END
