Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module Line where
- data Line = Line Double Double
- instance Show Line where
- show (Line 0 b) = "y = " ++ show b
- show (Line a b) = "y = " ++ show a ++ "x" ++ case signum b of
- 0 -> ""
- 1 -> " + " ++ show b
- _ -> " - " ++ show (-b)
- type Point = (Double, Double)
- type Equation = (Double, Double, Double)
- bestFitLine :: [Point] -> Line
- bestFitLine pts = uncurry Line $ solveSystem (reduce derivA) (reduce derivB)
- where
- derivA = map (\(x, y) -> mapThd (*x) (x, 1, -y)) pts
- derivB = map (\(x, y) -> (x, 1, -y)) pts
- solveSystem :: Equation -> Equation -> (Double, Double)
- solveSystem (a, b, c) (d, e, f) =
- let x = (b * f - e * c) / (a * e - b * d)
- in (x, (a * x + c) / (-b))
- reduce :: [Equation] -> Equation
- reduce = mapThd sum . unzip3
- mapThd :: (a -> b) -> (a, a, a) -> (b, b, b)
- mapThd f (a, b, c) = (f a, f b, f c)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement