gpt4 book ai didi

ruby - 使用 Ruby 注入(inject)计算嵌套总和

转载 作者:数据小太阳 更新时间:2023-10-29 07:31:25 24 4
gpt4 key购买 nike

我正在尝试使用 Ruby 的注入(inject)来对表示有限连分数的数组求和,其中

[a, b, c, d, e, ... , x] = a + 1/(b + 1/(c + 1/(d + 1/(e + ... 1/x)...)))

我不知道如何获得正确的嵌套评估以使用注入(inject)返回正确的值。

相反,我所写的只是返回项的平和而不是嵌套和。例如,

total = [0, 2, 1, 12, 8].inject do |sum,x|
sum = sum + Rational(1,x)
end
puts total
#=> 41/24

也就是说, 0 + 1/2 + 1/1 + 1/12 + 1/8 #=> 41/24代替 0 + 1/(2 + 1/(1 + 1/(12+1/8))) #=> 105/307,这是正确的值。

是否可以使用 inject 方法计算这种类型的总和?

如果不是,我该如何正确计算?

最佳答案

arr = [0, 2, 1, 12, 8]

arr.reverse.reduce { |tot, n| n + Rational(1, tot) }
#=> 105/307

步骤:

a = arr.reverse
#=> [8, 12, 1, 2, 0]
b = a.reduce do |tot ,n|
puts "tot=#{tot}, n=#{n}"
(n + Rational(1, tot)).tap { |r| puts " tot=#{r}" }
end
#=> (105/307)

这打印:

tot=8, n=12
tot=97/8
tot=97/8, n=1
tot=105/97
tot=105/97, n=2
tot=307/105
tot=307/105, n=0
tot=105/307

或者,可以使用递归。

def recurse(arr)
arr.size == 1 ? arr.first : arr.first + Rational(1, recurse(arr.drop(1)))
end

recurse arr
#=> (105/307)

关于ruby - 使用 Ruby 注入(inject)计算嵌套总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56917037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com