R:如何使用 gamma() return 实际数字而不是 Inf
R: how to have gamma() return the actual number instead of Inf
运行 gamma(200)
returns Inf
在 R 中。是否有可能以某种方式让 R return 成为实际数字?它看起来像 R.gamma(171.6)
return 和 Inf
以上的任何东西。
问题是您不能用双精度表示它:
gamma(200) # too large value
#R> [1] Inf
lgamma(200) # but log is not
#R> [1] 857.9337
exp(857) # the issue!
#R> [1] Inf
.Machine$double.xmax # maximum double value
#R> [1] 1.797693e+308
gamma(171) # almost there!
#R> [1] 7.257416e+306
您可以使用伽玛函数的对数来代替 lgamma
。否则你将需要使用比 R 的浮点精度更高的第三方库。
google 搜索表明,如果您不能使用 gamma 函数的对数,Rmpfr::igamma
函数可能就是您想要的:
Rmpfr::igamma(171, 0)
#R> 1 'mpfr' number of precision 53 bits
#R> [1] 7.257415615307999e+306
Rmpfr::igamma(200, 0)
#R> 1 'mpfr' number of precision 53 bits
#R> [1] 3.9432893368239526e+372
使用 Benjamin Cristoffersen 提出的 lgamma,您可以将有效数和指数(以 10 为底)计算为单独的变量:
(res <- gamma(100))
9.332622e+155
# Natural logarithm of result
(ln_res <- lgamma(100))
359.1342
# log base 10 of result
(log10_res <- ln_res/log(10))
155.97
# decimal part of the number above, raised to the 10th power
(significand_res <- 10 ^ (log10_res %% 1))
9.332622
# non-decimal part
(exp_res <- log10_res %/% 1)
155
对于 gamma(200)
这个 returns: 3.9432 * 10 ^ 372
运行 gamma(200)
returns Inf
在 R 中。是否有可能以某种方式让 R return 成为实际数字?它看起来像 R.gamma(171.6)
return 和 Inf
以上的任何东西。
问题是您不能用双精度表示它:
gamma(200) # too large value
#R> [1] Inf
lgamma(200) # but log is not
#R> [1] 857.9337
exp(857) # the issue!
#R> [1] Inf
.Machine$double.xmax # maximum double value
#R> [1] 1.797693e+308
gamma(171) # almost there!
#R> [1] 7.257416e+306
您可以使用伽玛函数的对数来代替 lgamma
。否则你将需要使用比 R 的浮点精度更高的第三方库。
google 搜索表明,如果您不能使用 gamma 函数的对数,Rmpfr::igamma
函数可能就是您想要的:
Rmpfr::igamma(171, 0)
#R> 1 'mpfr' number of precision 53 bits
#R> [1] 7.257415615307999e+306
Rmpfr::igamma(200, 0)
#R> 1 'mpfr' number of precision 53 bits
#R> [1] 3.9432893368239526e+372
使用 Benjamin Cristoffersen 提出的 lgamma,您可以将有效数和指数(以 10 为底)计算为单独的变量:
(res <- gamma(100))
9.332622e+155
# Natural logarithm of result
(ln_res <- lgamma(100))
359.1342
# log base 10 of result
(log10_res <- ln_res/log(10))
155.97
# decimal part of the number above, raised to the 10th power
(significand_res <- 10 ^ (log10_res %% 1))
9.332622
# non-decimal part
(exp_res <- log10_res %/% 1)
155
对于 gamma(200)
这个 returns: 3.9432 * 10 ^ 372