不确定如何通过递归实现标准偏差 [英] Not sure how to implement the standard deviation through recursion

查看:78
本文介绍了不确定如何通过递归实现标准偏差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我设置了以下通用方法:

So I have the generic method set up consisting of:

  • 类型为T的参数
  • T的列表(这是我要查看的数据集)
  • 从T到double的函数(此函数将用于从每个数据元素获取属性.因此 基本上,该属性用于计算和返回标准偏差.) 例如,列表(7.63、3.87、1.59、8.26、5.11、0.65、7.88)应返回3.100496888
  • A parameter of type T
  • A List of T's (which will be the data set that I will be looking at)
  • A function from T to double (This function will be used to take a property from each data element. So basically the property is used to compute the and return standard deviation.) For example the List(7.63, 3.87, 1.59, 8.26, 5.11, 0.65, 7.88) should return 3.100496888

最后一个项目符号使我感到困惑,我不确定如何将其放在递归形式中.

That last bullet is confusing me and I'm not sure how to put it in the form of recursion.

```
  def standardDeviation[T](elements: List[T], property: T => Double): Double = {

  }
```

对不起,我缺乏经验.函数式编程并不是我的强项.

Sorry for my lack of experience. Functional programming is just not my strong spot.

推荐答案

如果您不想更改签名,则必须使用局部函数并使该函数尾递归

If you don't want to change the signature you would have to use local function and make that function tail-recursive

def standardDeviation[T](elements: List[T], property: T => Double): Double = {
  val values = elements.map(property)
  val size = elements.size.toDouble
  // this could acually be replaced by values.sum
  @scala.annotation.tailrec
  def calculateSum(remaining: List[Double], acc: Double): Double = remaining match {
    case head :: tail => calculateSum(tail, acc + head)
    case Nil          => acc
  }
  val mean = calculateSum(values, 0.0) / size
  @scala.annotation.tailrec
  def calculateSumOfDiffs(remaining: List[Double], acc: Double): Double = remaining match {
    case head :: tail => calculateSumOfDiffs(tail, acc + Math.pow(head - mean, 2.0))
    case Nil          => acc
  }
  Math.sqrt(calculateSumOfDiffs(values, 0.0) / (size - 1))
}

进行尾部递归计算时,必须以某种方式到目前为止传递结果,因此,如果无法在API中公开中间结果,这是唯一的方法.

When you are doing tail recursive computation you have to somehow pass results-so-far, so if you cannot expose the intermediate results in API, this is the only way.

但是,您不必使用tail rec来实现此目的,而是可以使用一些功能性方法来实现:

However, you don't have to implement this using tail rec, but instead use some functional approach instead:

def standardDeviation[T](elements: List[T], property: T => Double): Double = {
  val values = elements.map(property)
  val size = values.size.toDouble
  val mean = values.sum / size
  Math.sqrt(values.map(x => Math.pow(x - mean, 2.0)).sum / (size - 1))
}

这篇关于不确定如何通过递归实现标准偏差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆