#
# Results:
#	Returns x!, the factorial of x.
#
# Side effects:
#	None.
#
# For integer x, 0 <= x <= 12, an exact integer result is returned.
#
# For integer x, 13 <= x <= 21, an exact floating-point result is returned
# on machines with IEEE floating point.
#
# For integer x, 22 <= x <= 170, the result is exact to 1 ULP.
#
# For real x, x >= 0, the result is approximated by computing
# Gamma(x+1) using the ::math::ln_Gamma function, and the result is
# expected to be precise to better than nine significant figures.
#
# It is an error to present x <= -1 or x > 170, or a value of x that
# is not numeric.
#
#----------------------------------------------------------------------

proc ::math::factorial { x } {

    variable factorialList

    # Common case: factorial of a small integer

    if { [string is integer $x]
	 && $x >= 0
	 && $x <= [llength $factorialList] } {
	return [lindex $factorialList $x]
    } 

    # Error case: not a number

    if { ![string is double $x] } {
	return -code error [expectDouble $x]
    } 

    # Error case: gamma in the left half plane

    if { $x <= -1.0 } {
	set proc [lindex [info level 0] 0]
	set message "argument to $proc must be greater than -1.0"
	return -code error -errorcode [list ARITH DOMAIN $message] $message
    } 

    # Error case - gamma fails

    if { [catch { expr {exp( [ln_Gamma [expr { $x + 1 }]] )} } result] } {
	return -code error -errorcode $::errorCode $result
    } 

    # Success - computed factorial n as Gamma(n+1)

    return $result

}
