PageRenderTime 41ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/Task/Numeric-error-propagation/Haskell/numeric-error-propagation.hs

https://github.com/acmeism/RosettaCodeData
Haskell | 20 lines | 16 code | 4 blank | 0 comment | 0 complexity | 45681a0b57411b7900fb9a09c906a998 MD5 | raw file
  1. data Error a = Error {value :: a, uncertainty :: a} deriving (Eq, Show)
  2. instance (Floating a) => Num (Error a) where
  3. Error a ua + Error b ub = Error (a + b) (sqrt (ua ^ 2 + ub ^ 2))
  4. negate (Error a ua) = Error (negate a) ua
  5. Error a ua * Error b ub = Error (a * b) (abs (a * b * sqrt ((ua / a) ^ 2 + (ub / b) ^ 2))) -- I've factored out the f^2 from the square root
  6. fromInteger a = Error (fromInteger a) 0
  7. instance (Floating a) => Fractional (Error a) where
  8. fromRational a = Error (fromRational a) 0
  9. Error a ua / Error b ub = Error (a / b) (abs (a / b * sqrt ((ua / a) ^ 2 + (ub / b) ^ 2))) -- I've factored out the f^2 from the square root
  10. instance (Floating a) => Floating (Error a) where
  11. Error a ua ** Error c 0 = Error (a ** c) (abs (ua * c * a**c / a))
  12. main = print (sqrt ((x1 - x2) ** 2 + (y1 - y2) ** 2)) where -- using (^) for exponentiation would calculate a*a, which the problem specifically said was calculated wrong
  13. x1 = Error 100 1.1
  14. y1 = Error 50 1.2
  15. x2 = Error 200 2.2
  16. y2 = Error 100 2.3