我正在使用计算方差的F#函数。我试图逐步完成每次迭代以获得正确的答案,但我认为我在某个地方偏离轨道,因为我一直得到错误的答案。有人可以请我完成这个功能的一次迭代,让我回到正轨
let variance values
let average = Seq.average values
let length = Seq.length values
values
|> Seq.map (fun x -> 1.0 / float length * (x - average) ** 2.0)
|> Seq.sum
来电是variance [1.0..6.0]
对我来说,传递的第一个值是1.0
,因此它是(1.0 / 6 * (1.0-3.5) ** 2.0)
,因此.166 * -2.5 ** 2.0
我也不确定**
在公式I中的含义是假设乘以。
正确答案应为2.9166666667
答案 0 :(得分:0)
为了便于理解,您可以按如下方式重写代码:
let variance values =
let average = Seq.average values
let length = Seq.length values
let sum = values
|> Seq.map (fun x -> (x - average) ** 2.0)
|> Seq.sum in sum / float length
variance [1.0..6.0] |> printfn "%A"
打印:2.916666667
链接:https://dotnetfiddle.net/09PHXn
通过迭代:
let variancetest values =
let average = Seq.average values
let length = Seq.length values
values
|> Seq.iteri(fun i x ->
printfn "%i [%f]: %f ^ 2 = %A" i x (x - average) ((x - average) ** 2.0))
let sum = values
|> Seq.map (fun x -> (x - average) ** 2.0)
|> Seq.sum
let flength = float length
printfn "Sum = %f" sum
printfn "1/length = %f" (1.0 / flength)
printfn "Result / length = %f" (sum / flength)
variancetest [1.0..6.0]
打印:
0 [1.000000]: -2.500000 ^ 2 = 6.25
1 [2.000000]: -1.500000 ^ 2 = 2.25
2 [3.000000]: -0.500000 ^ 2 = 0.25
3 [4.000000]: 0.500000 ^ 2 = 0.25
4 [5.000000]: 1.500000 ^ 2 = 2.25
5 [6.000000]: 2.500000 ^ 2 = 6.25
Sum = 17.500000
1/length = 0.166667
Result / length = 2.916667