简体   繁体   English

尾数递归函数

[英]Tail Recursive function for the sum of fractions

I am trying to convert this recursive function into a tail recursive function 我正在尝试将此递归函数转换为尾递归函数

def sumOfFractions(n: Int): Double = {
  require(n > 0, "Parameter n has to be greater than 0");
  if (n==1)
    1.0
  else
    1.0 / n + sumOfFractions(n - 1)
}

I thought that this solution would work but when it runs it just returns 1.0 我以为这个解决方案会起作用,但是当它运行时只会返回1.0

def sumOfFractions(n:Int):Double = {

  def inner(acc:Int, n:Int): Double={
    if(n <= 1)1.0
    else
    {
        inner(acc+(1/n),n-1)
    }

  }

  inner(0,n)
}

I think this is because the accumulator is not being updated correctly but I don't understand why. 我认为这是因为累加器未正确更新,但我不明白为什么。 The code is in Scala but an example in any language would be helpful. 该代码在Scala中,但是任何语言的示例都将有所帮助。

You need the base case ( n <= 1 ) to return the accumulator, not 1.0 . 您需要基本情况​​( n <= 1 )返回累加器,而不是1.0 You'll also run into problems because the accumulator is an Int instead of a Double , which means that + (1 / n) is just adding 0 (the result of dividing 1: Int by any n: Int greater than one). 您还会遇到问题,因为累加器是Int而不是Double ,这意味着+ (1 / n)仅加01: Int除以任何n: Int大于1的结果)。

You can fix this by changing acc 's type and making the numerator of the reciprocal a literal double: 您可以通过更改acc的类型并将倒数分子设为文字双精度字来解决此问题:

def sumOfFractions(n: Int):Double = {
  def inner(acc: Double, n: Int): Double =
    if (n <= 1) acc else inner(acc + (1.0 / n), n - 1)

  inner(0, n)
}

This should work. 这应该工作。

Correct your code 更正您的代码

1) Return acc (accumulator) when n <= 1 1)当n <= 1时返回acc(累加器)

2) Your acc should be Double type 2)您的帐户应为Double类型

3) Division should be floating point division 3)除法应为浮点除法

def sumOfFractions(n: Int): Double = {

  def inner(acc: Double, n:Int): Double = if(n <= 1) acc  
     else inner(acc + (1.0 / n), n - 1)

  inner(0,n)
}

Using foldLeft 使用foldLeft

  def sumOfFractions(n: Int): Double = 
    (1 to n).foldLeft(0.0)((r, c) => r + (1.0 / c))

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

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