Advertisement
Guest User

Haskell: Line of best-fit

a guest
Jan 22nd, 2020
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Line where
  2.  
  3. data Line = Line Double Double
  4.  
  5. instance Show Line where
  6.     show (Line 0 b) = "y = " ++ show b
  7.     show (Line a b) = "y = " ++ show a ++ "x" ++ case signum b of
  8.         0 -> ""
  9.         1 -> " + " ++ show b
  10.         _ -> " - " ++ show (-b)
  11.  
  12. type Point = (Double, Double)
  13. type Equation = (Double, Double, Double)
  14.  
  15. bestFitLine :: [Point] -> Line
  16. bestFitLine pts = uncurry Line $ solveSystem (reduce derivA) (reduce derivB)
  17.   where
  18.     derivA = map (\(x, y) -> mapThd (*x) (x, 1, -y)) pts
  19.     derivB = map (\(x, y) -> (x, 1, -y)) pts
  20.  
  21. solveSystem :: Equation -> Equation -> (Double, Double)
  22. solveSystem (a, b, c) (d, e, f) =
  23.     let x = (b * f - e * c) / (a * e - b * d)
  24.      in (x, (a * x + c) / (-b))
  25.  
  26. reduce :: [Equation] -> Equation
  27. reduce = mapThd sum . unzip3
  28.  
  29. mapThd :: (a -> b) -> (a, a, a) -> (b, b, b)
  30. mapThd f (a, b, c) = (f a, f b, f c)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement