简体   繁体   English

R:尝试编写等效函数n选择k时出错

[英]R: error when trying to write an equivalent function n choose k

I'm taking the class of introduction for R programming. 我正在学习R编程入门课程。

we were asked to write a function that will be the same as n choose k: 我们被要求编写一个与n选择k相同的函数:

choose(n, k)

we were asked to check if the function works by running n = 200, k = 50. 我们被要求通过运行n = 200,k = 50来检查函数是否起作用。

I wrote the following code: 我写了以下代码:

    select_k <- function(n, k){
  sr <- c(log10(log10((factorial(n-1)/factorial(k-1)*factorial(n-k-2)))*(n/k)))
  return(sr)
}

as select_k is supposed to be the " n choose k". 因为select_k应该是“ n选择k”。

my function works with values such as: 100 choose 25, but it doesn't work with greater values, like n = 200, k = = 50. 我的函数可以使用以下值:100选择25,但不适用于更大的值,例如n = 200,k = = 50。

select_k( n = 200, k = 50)
[1] NaN
Warning message:
In factorial(n) : value out of range in 'gammafn'

I have no idea what else can be done to fix that. 我不知道还有什么可以解决的。

This doesn't work for larger n because factorial(n) is too big: 这对于较大的n无效,因为factorial(n)太大:

> factorial(199)
[1] Inf
Warning message:
In factorial(199) : value out of range in 'gammafn'

This should return 200, but the computer only sees that you are trying to divide Inf by Inf : 这应该返回200,但是计算机只会看到您正在尝试将Inf除以Inf

> factorial(200)/factorial(199)
[1] NaN
Warning messages:
1: In factorial(200) : value out of range in 'gammafn'
2: In factorial(199) : value out of range in 'gammafn'

Obviously a lot of the multiplications in "n choose k" cancel out, so you'll need to avoid using regular factorial and only multiply the numbers that don't cancel out ( ?prod might be useful for you). 显然,“ n select k”中的许多乘法都被抵消,因此您需要避免使用常规阶乘,而仅将未抵消的数字相乘( ?prod可能对您有用)。 Or (probably better) use the log version lfactorial to avoid running into numbers your computer can't store. 或者(可能更好)使用日志版本号lfactorial以避免lfactorial计算机无法存储的数字。

Edit: Added lfactorial recommendation from @MrFlick's comment 编辑:从@MrFlick的评论中添加了lfactorial推荐

Have a look at this { 看看这个{

a <- function(n, k) {
  exp(lgamma(n+1) - lgamma(n - k + 1) - lgamma(k + 1) )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM