0

我有一个代码来计算标准偏差:

Public Function StandardDeviation(ByRef arr() As Double) As Double

'standard deviation
Dim sum As Double
Dim sumSquare As Double
Dim value As Double
Dim count As Long
Dim index As Long
sum = 0
sumSquare = 0
value = 0
count = 0
index = 0

' evaluate sum of values
For index = LBound(arr) To UBound(arr)
    value = arr(index)
    count = count + 1
    sum = sum + value
    sumSquare = sumSquare + value * value
Next

StandardDeviation = Sqr((sumSquare - (sum * sum / count)) / count)

End Function

它似乎工作正常。

碰巧的是,这些值有时都是相同的,例如:

    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645
    0.419208025523645

在这种情况下,我在这一行中收到错误“无效参数”:

StandardDeviation = Sqr((sumSquare - (sum * sum / count)) / count)

有人看到我的错误吗?

4

2 回答 2

3

我的猜测是你遇到了一个问题,你“试​​图”取负值的平方根。当数字都相同时,sumSquare 应该与 (sum * sum / count) 相同。

我建议使用以下代码。

If ((sum * sum / count)) > sumSquare Then
    StandardDeviation = 0
Else
    StandardDeviation = Sqr((sumSquare - (sum * sum / count)) / count)
End If
于 2013-01-13T19:49:41.870 回答
0

您可以通过删除循环外的计数器来加快计算速度

For index = LBound(arr) To UBound(arr)
  value = arr(index)
  sum = sum + value
  sumSquare = sumSquare + value * value
Next

count = UBound(arr) - LBound(arr)  + 1
于 2013-01-20T15:11:54.543 回答