special-functions/beta.ss
#lang scheme/base
;;; PLT Scheme Science Collection
;;; special-functions/beta.ss
;;; Copyright (c) 2006-2008 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 beta special function.
;;;
;;; Version Date      Description
;;; 1.0.0   02/08/06  Initial implementation. (Doug Williams)
;;; 2.0.0   11/17/07  Added unchecked version of function and getting
;;;                   ready for PLT Scheme v4.0 (Doug Williams)
;;; 3.0.0   06/09/08  Changes required for V4.0.  (Doug Williams)

(require (lib "contract.ss"))

(provide
 (rename-out (beta unchecked-beta)
             (lnbeta unchecked-lnbeta)))

(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 (unchecked-gamma* x))
               (gsy (unchecked-gamma* y))
               (gsxy (unchecked-gamma* (+ x y)))
               (lnopr (unchecked-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 (unchecked-lngamma x))
               (lgy (unchecked-lngamma y))
               (lgxy (unchecked-lngamma (+ x y))))
          (+ lgx lgy (- lgxy))))))

(define (beta x y)
  (if (and (< x 50.0)
           (< y 50.0))
      (let ((gx (unchecked-gamma x))
            (gy (unchecked-gamma y))
            (gxy (unchecked-gamma (+ x y))))
        (/ (* gx gy) gxy))
      (exp (lnbeta x y))))