这个问题对我来说似乎很简单,但我找不到答案.
假设您要从正态分布中获取大小为n的样本,其均值为10,方差为1,然后得到它们的平均值和方差,以验证样本是否来自正态分布.
我想这会是这样的:
values = take n $ sample (normal 10 1) (avg values, variance values)
我正在尝试使用库random-fu,所以如果你能用lib提供答案,我真的很感激.
这里的尴尬总是存在于Haskell中的随机性 - 因为Haskell是纯粹的,你需要有某种"随机"源.random-fu
使用RandomSource
这个目的,那么你这个单子里面,当你想操纵随机值工作.
import Data.Random import Control.Monad (replicateM) average :: [Double] -> Double average xs = sum xs / fromIntegral (length xs) variance :: [Double] -> Double variance xs = average [ (x - m)^2 | x <- xs ] where m = average xs main :: IO () main = do sample <- runRVar (replicateM 10 (normal 10 1)) StdRandom :: IO [Double] putStrLn $ "Average: " ++ show (average sample) putStrLn $ "Variance: " ++ show (variance sample)
试运行似乎给了我合理的输出:
ghci> main Average: 10.294887142436771 Variance: 0.7129578122237161 ghci> main Average: 9.677325092160597 Variance: 0.9894150286175698 ghci> main Average: 9.714089727813253 Variance: 1.0279068711054316 ghci> main Average: 10.32028785267642 Variance: 0.8574243439019995 ghci> main Average: 9.696843993234065 Variance: 0.45301180269725994