【问题标题】:Getting wrong answer when calculating geometric series计算几何级数时得到错误答案
【发布时间】:2021-06-17 10:35:43
【问题描述】:

我正在尝试使用 tidyverse 累加函数来计算两个几何级数。

这个几何级数的结果应该是 1871.445

我尝试使用以下代码行,得到答案 1200

sum(accumulate(seq(from=0, to=4, by=1/12), .init = 400, ~ .x/(1 + 0.5)))

我也在尝试计算这个几何级数:

这应该给出 4.678613 的结果,但我的代码行给了我 3

sum(accumulate(seq(from=0, to=4, by=1/12), .init = 1, ~ .x*(1/(1 + 0.5))))

【问题讨论】:

    标签: r tidyverse accumulate


    【解决方案1】:

    accumulate 用于之前迭代的结果用于任何序列的下一项。 此外,R 的美妙之处在于它的矢量化操作。所以你可以直接做。我还添加了accumulate 的做法,但您可能会注意到参数.x 从未使用过,因此当快捷方式可用时,它相当于走更长的路线。

    # 1st series
    400/(1.5^((0:4)/12))
    #> [1] 400.0000 386.7103 373.8621 361.4408 349.4322
    
    #accumualate style (though redundant)
    purrr::accumulate(0:4, .init = 0, ~400/(1.5 ^(.y/12)))[-1]
    #> [1] 400.0000 386.7103 373.8621 361.4408 349.4322
    
    # its sum
    sum(400/(1.5^((0:4)/12)))
    #> [1] 1871.445
    
    #2nd series
    (1/(1 + 0.5))^((0:4)/12)
    #> [1] 1.0000000 0.9667757 0.9346553 0.9036020 0.8735805
    
    #accumulate style
    purrr::accumulate(0:4, .init = 0, ~(1/(1 + 0.5))^(.y/12))[-1]
    #> [1] 1.0000000 0.9667757 0.9346553 0.9036020 0.8735805
    
    #sum
    sum((1/(1 + 0.5))^((0:4)/12))
    #> [1] 4.678613
    

    reprex package (v2.0.0) 于 2021-06-17 创建

    【讨论】:

      【解决方案2】:

      你在这里不需要accumulate,它的使用并没有增加任何有价值的东西;您正在执行的累积只是 sum - 所以使用(仅)sum:

      t = seq(0, 5 - 1)
      sum(400 / (1.5 ^ (t / 12)))
      

      可以使用accumulate(或者更确切地说,它的兄弟reduce!)而不是 sum,但生成的代码会更复杂,因为没有额外的收获。但是,即使您使用了reduce,您对等式的转录也是错误的。

      【讨论】:

        猜你喜欢
        • 2021-08-12
        • 1970-01-01
        • 2022-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-12
        • 2020-01-06
        • 2019-05-06
        相关资源
        最近更新 更多