I am trying to make a skewness function in F# using Knuth's re开发者_如何学JAVAcursive formula, based on the formula for the variance in Jon Harrop's F# for scientists.
Here is my code, (with an auxilliary function)
let skewness_aux (m, m2, m3, k) x =
let m' = m + (x - m)/k
let m2' = m2 + ((x - m)*(x - m)*(k-1.0))/k
m', m2', m3 + (x-m)*(x-m)*(x-m)*(k-1.0)*(k-2.0)/(k*k)-(3.0*(x-m)*m2)/k, k + 1.0;;
let skewness xs =
let _, m2, m3, n2 = Seq.fold skewness_aux (0.0, 0.0, 0.0, 1.0) xs
(sqrt(n2) * m3)/(sqrt (m2*m2*m2));;
And finally a little test -
skewness [|2.0; 2.0; 3.0|];;
Which should return 1/(sqrt2) approx 0.707107, but is instead giving me 0.8164965809
Any wiser heads than mine got any advice on why it isn't working? The formulas look correct. I am using the wikipedia page on algorithms for higher moment functions as well as Pebay's 2008 paper on the subject to cross check.
Many thanks in advance for any and all help.
Your skewness_aux
function returns m, m2, m3, and k+1. Therefore, you need to use sqrt(n2-1), not sqrt(n2).
精彩评论