使用 Ruby 注入计算嵌套总和

reg*_*lus 4 ruby inject

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

[a, b, c, d, e, ... , x] = a + 1/(b + 1/(c + 1/(d + 1/(e + ... 1/x)...)))
Run Code Online (Sandbox Code Playgroud)

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

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

[a, b, c, d, e, ... , x] = a + 1/(b + 1/(c + 1/(d + 1/(e + ... 1/x)...)))
Run Code Online (Sandbox Code Playgroud)

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

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

如果不是,我怎样才能正确计算它?

Car*_*and 5

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

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

步骤:

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) 
Run Code Online (Sandbox Code Playgroud)

这打印:

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
Run Code Online (Sandbox Code Playgroud)

或者,可以使用递归。

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

recurse arr
  #=> (105/307)
Run Code Online (Sandbox Code Playgroud)

  • 唔。`arr.reverse.inject{ |sum, i| i + 有理数(1, 总和) }` (2认同)