special-functions/beta.ss
;;; PLT Scheme Science Collection
;;; special-functions/beta.ss
;;; Copyright (c) 2006 M. Douglas Williams
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 2.1 of the License, or (at your option) any later version.
;;;
;;; This library is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free
;;; Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
;;; 02111-1307 USA.
;;;
;;; -------------------------------------------------------------------
;;;
;;; This is the module for the gamma, psi, and zeta special functions.
;;; They are provided as a single module to avoid circular module
;;; definitions.
;;;
;;; Version Date      Description
;;; 1.0.0   02/08/06  Initial implementation. (Doug Williams)

(module beta mzscheme
  
  (require (lib "contract.ss"))
  
  (provide/contract
   (beta 
    (-> (>/c 0.0) (>/c 0.0) real?))
   (lnbeta
    (-> (>/c 0.0) (>/c 0.0) real?)))
  
  (require "../math.ss")
  (require "gamma.ss")
  
  (define (lnbeta x y)
    (let* ((xymax (max x y))
           (xymin (min x y))
           (rat (/ xymin xymax)))
      (if (< rat 0.2)
          ;; min << max, so be careful with the subtraction
          (let* ((gsx (gammastar x))
                 (gsy (gammastar y))
                 (gsxy (gammastar (+ x y)))
                 (lnopr (log1p rat))
                 (lnpre (log (* (/ (* gsx gsy) gsxy)
                                sqrt2 sqrtpi)))
                 (t1 (* xymin (log rat)))
                 (t2 (* 0.5 (log xymin)))
                 (t3 (* (+ x y -0.5) lnopr))
                 (lnpow (- t1 t2 t3)))
            (+ lnpre lnpow))
          (let* ((lgx (lngamma x))
                 (lgy (lngamma y))
                 (lgxy (lngamma (+ x y))))
            (+ lgx lgy (- lgxy))))))
  
  (define (beta x y)
    (if (and (< x 50.0)
             (< y 50.0))
        (let ((gx (gamma x))
              (gy (gamma y))
              (gxy (gamma (+ x y))))
          (/ (* gx gy) gxy))
        (exp (lnbeta x y))))
  
)