用于计算序列总数的函数

时间:2017-10-24 10:45:59

标签: r

我正在尝试计算R中此序列的总和。

在下面的情况下,序列将有两个输入(1和11),

1 + (1 * 2/3 ) + (1 * 2/3 * 4/5) + ( 1 * 2/3 * 4/5 * 6/7) + ....................(1 *......10/11)

我认为,定义我自己的是去这里的方式。

4 个答案:

答案 0 :(得分:4)

你可以尝试在这里使用老式循环:

sum <- 0
num_terms <- 6
for (i in 1:num_terms) {
    y <- 1
    if (i > 1) {
        for (j in 1:(i-1)) {
            y <- y * (j*2 / (j*2 + 1))
        }
    }
    sum <- sum + y
}

您可以将num_terms设置为您想要的任何值,从1到更高的值。在这种情况下,我使用6条款,因为这是您问题中所请求的条款数量。

有人可能会将上面的整个代码片段缩小到一行,但在我看来,这里有一个明确的循环。

以下是演示的链接,该演示打印出每个条款中使用的值,以便进行验证:

Demo

答案 1 :(得分:2)

我的方法:

# input
start <- 1
n <- 5 # number of terms

end <- start + n*2

result <- start
to_add <- start

for (i in (start + 1):(end-1)) {
  to_add <- to_add * (i / (i + 1))
  result <- result + to_add
}

给出:

> result
[1] 4.039755

答案 2 :(得分:1)

使用cumprod生成内部术语的另一个基本R替代方法是

sum(cumprod(c(1, seq(2, 10, 2)) / c(1, seq(3, 11, 2))))
[1] 3.4329

此处,c(1, seq(2, 10, 2)) / c(1, seq(3, 11, 2))生成序列1,2 / 3,4 / 5,6 / 7,8 / 9,10 / 11,cumprod生成累积积。此结果与sum相加。返回的结果与接受的答案中的结果相同。

答案 3 :(得分:1)

你可以尝试:

for (String resourcebundle : bundleNames) {
        String bundleName =
        resourcebundle + (bundlePostfix == null ? "" : bundlePostfix);
        try {
              bundle =  ResourceBundle.getBundle(bundleName, locale, getCurrentLoader(bundleName));

        } catch (MissingResourceException e) {
            // bundle with this name not found;
        }

        if (bundle == null)
            continue;
        try {
            message = bundle.getString(key);
            if (message != null)
                break;
        } catch (Exception e) {
    }
} 

enter image description here