Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
class method
Math.gamma
(::Math::double x) -> ::Float
Math.gamma(x) → float
math.c
View on GitHub ↗
static VALUE
math_gamma(VALUE unused_obj, VALUE x)
{
static const double fact_table[] = {
/* fact(0) */ 1.0,
/* fact(1) */ 1.0,
/* fact(2) */ 2.0,
/* fact(3) */ 6.0,
/* fact(4) */ 24.0,
/* fact(5) */ 120.0,
/* fact(6) */ 720.0,
/* fact(7) */ 5040.0,
/* fact(8) */ 40320.0,
/* fact(9) */ 362880.0,
/* fact(10) */ 3628800.0,
/* fact(11) */ 39916800.0,
/* fact(12) */ 479001600.0,
/* fact(13) */ 6227020800.0,
/* fact(14) */ 87178291200.0,
/* fact(15) */ 1307674368000.0,
/* fact(16) */ 20922789888000.0,
/* fact(17) */ 355687428096000.0,
/* fact(18) */ 6402373705728000.0,
/* fact(19) */ 121645100408832000.0,
/* fact(20) */ 2432902008176640000.0,
/* fact(21) */ 51090942171709440000.0,
/* fact(22) */ 1124000727777607680000.0,
/* fact(23)=25852016738884976640000 needs 56bit mantissa which is
* impossible to represent exactly in IEEE 754 double which have
* 53bit mantissa. */
};
enum {NFACT_TABLE = numberof(fact_table)};
double d;
d = Get_Double(x);
/* check for domain error */
if (isinf(d)) {
if (signbit(d)) domain_error("gamma");
return DBL2NUM(HUGE_VAL);
}
if (d == 0.0) {
return signbit(d) ? DBL2NUM(-HUGE_VAL) : DBL2NUM(HUGE_VAL);
}
if (d == floor(d)) {
domain_check_min(d, 0.0, "gamma");
if (1.0 <= d && d <= (double)NFACT_TABLE) {
return DBL2NUM(fact_table[(int)d - 1]);
}
}
return DBL2NUM(tgamma(d));
}
Returns the value of the gamma function for x.
-
Domain:
(-INFINITY, INFINITY]excluding negative integers. -
Range:
[-INFINITY, INFINITY].
Examples:
Example
gamma(-2.5) # => -0.9453087204829431 gamma(-1.5) # => 2.3632718012073513 gamma(-0.5) # => -3.5449077018110375 gamma(0.0) # => Infinity gamma(1.0) # => 1.0 gamma(2.0) # => 1.0 gamma(3.0) # => 2.0 gamma(4.0) # => 6.0 gamma(5.0) # => 24.0
Related: Math.lgamma.