Created
July 16, 2015 07:34
-
-
Save edofic/939fd82aa76e9d614a50 to your computer and use it in GitHub Desktop.
fixed precision arithmetic in haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.Ratio ((%)) | |
import GHC.Real | |
-- 10 decimal places | |
newtype Fixed = Fixed Integer deriving (Eq, Ord, Enum) | |
instance Show Fixed where | |
show (Fixed a) = show whole ++ "." ++ trailing where | |
(whole, part) = a `divMod` (10 ^ 10) | |
digits = show part | |
trailing = replicate (10 - (length digits)) '0' ++ digits | |
instance Num Fixed where | |
fromInteger n = Fixed (n * 10 ^ 10) | |
Fixed a + Fixed b = Fixed (a + b) | |
Fixed a - Fixed b = Fixed (a - b) | |
Fixed a * Fixed b = Fixed ((a * b) `div` 10 ^ 10) | |
abs (Fixed a) = Fixed (abs a) | |
signum (Fixed a) = fromInteger (signum a) | |
instance Real Fixed where | |
toRational (Fixed a) = a % (10 ^ 10) | |
instance Integral Fixed where | |
toInteger (Fixed a) = a `div` 10 ^ 10 | |
Fixed a `quotRem` Fixed b = (fromInteger q, Fixed r) where | |
(q, r) = a `quotRem` b | |
instance Fractional Fixed where | |
fromRational (e :% d) = fromInteger e / fromInteger d | |
Fixed a / Fixed b = Fixed (a * 10 ^ 10 `div` b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment