Normal probability density function - GSL equivalent in Haskell

519 views Asked by At

I am trying to find the best way to draw from a normal distribution. I want to be able to use the normal probability density function (and its cumulative) in Haskell.

To put it simply, I want to use the functions on this page without using the GSL binding... I am struggling to find the right package. Which one would you say is the best?

Thank you and have a great day!

2

There are 2 answers

0
Emily On BEST ANSWER

Here's an example which uses random-fu:

import Data.Random    -- for randomness
import Text.Printf    -- for printf
import Data.Foldable  -- for the for_ loop

-- pdf and cdf are basically “Distribution -> Double -> Double”

main = do
  -- defining normal distribution with mean = 10 and variation = 2
  let normal = Normal (10 :: Double) 2
  -- CDF
  for_ [0..10] $ \i ->
    printf "cdf(%2d): %.4f\n" i (cdf normal (fromInteger i))
  -- PDF
  putStrLn "---"
  for_ [0..10] $ \i ->
    printf "pdf(%2d): %.4f\n" i (pdf normal (fromInteger i))

Run it and you'll see the following output:

cdf( 0): 0.0000
cdf( 1): 0.0000
cdf( 2): 0.0000
cdf( 3): 0.0002
cdf( 4): 0.0013
cdf( 5): 0.0062
cdf( 6): 0.0228
cdf( 7): 0.0668
cdf( 8): 0.1587
cdf( 9): 0.3085
cdf(10): 0.5000
---
pdf( 0): 0.0000
pdf( 1): 0.0000
pdf( 2): 0.0001
pdf( 3): 0.0004
pdf( 4): 0.0022
pdf( 5): 0.0088
pdf( 6): 0.0270
pdf( 7): 0.0648
pdf( 8): 0.1210
pdf( 9): 0.1760
pdf(10): 0.1995

There are 2 important points here:

  • Normal is a constructor defining a distribution. There are other distributions, such as Uniform, etc. Distributions have different types, but they all belong to the Distribution class.

  • pdf and cdf are class methods, which can operate on many distributions (perhaps not all, but many). The 1st parameter is the distribution and the 2nd – point at which PDF/CDF should be evaluated.

1
jhickner On

I think the statistics package can do what you want. Take a look here for what you can do with a distribution (pdf, etc.)

The ContGen instance should get you random numbers drawn from the distribution.

The normal distribution is here.