Skip to content

Commit

Permalink
Make standardize return Nothing is stddev couldn't be computed
Browse files Browse the repository at this point in the history
Add specializations and INLINABLE pragmas & expand documentation
  • Loading branch information
Shimuuar committed Nov 19, 2017
1 parent 6cc8cfd commit e0484f1
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions Statistics/Sample/Normalize.hs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,27 @@ module Statistics.Sample.Normalize
) where

import Statistics.Sample
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic as G
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Storable as S

-- | /O(n)/ Normalize a sample using standard scores.
standardize :: (G.Vector v Double) => v Double -> v Double
standardize xs = G.map (\x -> (x - mu) / sigma) xs
-- | /O(n)/ Normalize a sample using standard scores:
--
-- \[ z = \frac{x - \mu}{\sigma} \]
--
-- Where μ is sample mean and σ is standard deviation computed from
-- unbiased variance estimation. If sample to small to compute σ or
-- it's equal to 0 @Nothing@ is returned.
standardize :: (G.Vector v Double) => v Double -> Maybe (v Double)
standardize xs
| G.length xs < 2 = Nothing
| sigma == 0 = Nothing
| otherwise = Just $ G.map (\x -> (x - mu) / sigma) xs
where
mu = mean xs
mu = mean xs
sigma = stdDev xs
{-# INLINABLE standardize #-}
{-# SPECIALIZE standardize :: V.Vector Double -> Maybe (V.Vector Double) #-}
{-# SPECIALIZE standardize :: U.Vector Double -> Maybe (U.Vector Double) #-}
{-# SPECIALIZE standardize :: S.Vector Double -> Maybe (S.Vector Double) #-}

0 comments on commit e0484f1

Please sign in to comment.