packages feed

hsmt-0.1.0.0: src/HSMT/Core/Float.hs

-- | Reference semantics of the SMT-LIB theory of floating-point numbers
-- (IEEE 754-2008, binary formats).
--
-- A floating-point value of the format @(eb, sb)@ (exponent width @eb@,
-- significand width @sb@ including the hidden bit, both at least 2) is kept
-- as its IEEE bit pattern of @eb + sb@ bits. SMT-LIB has a single NaN, so
-- every NaN pattern is replaced by the canonical one ('canonicalNaN'):
-- equal values then have equal patterns.
--
-- Operations are computed exactly on rationals and rounded once, which is
-- the definition of IEEE arithmetic. Results that SMT-LIB leaves
-- unspecified (@fp.min@ and @fp.max@ of zeros of different signs,
-- conversions to bit-vectors of NaN, infinities and values out of range)
-- are 'Nothing'.
module HSMT.Core.Float
  ( RoundingMode (..)
  , allRoundingModes
  , rmName
    -- * Bit patterns
  , FP (..)
  , decode
  , encode
  , canonicalNaN
  , canonicalize
  , isNaNBits
  , fpWidth
  , fpBias
  , fpFromFields
  , fpToRational
    -- * Rounding
  , roundRational
  , roundToInteger
    -- * Operations
  , fpAbs
  , fpNeg
  , fpAdd
  , fpSub
  , fpMul
  , fpDiv
  , fpFma
  , fpSqrt
  , fpRem
  , fpRoundToIntegral
  , fpMin
  , fpMax
  , fpLeq
  , fpLt
  , fpEq
  , fpIsNormal
  , fpIsSubnormal
  , fpConvert
  , fpFromInteger
  , fpToInteger
  ) where

import Data.Bits (shiftL, shiftR, testBit, (.&.), (.|.))
import Data.Ratio (denominator, numerator, (%))
import Data.Text (Text)

-- | The five IEEE rounding modes.
data RoundingMode
  = RNE
    -- ^ Round to nearest, ties to even.
  | RNA
    -- ^ Round to nearest, ties away from zero.
  | RTP
    -- ^ Round towards positive infinity.
  | RTN
    -- ^ Round towards negative infinity.
  | RTZ
    -- ^ Round towards zero.
  deriving (Eq, Ord, Show, Enum, Bounded)

-- | Every rounding mode, in declaration order.
allRoundingModes :: [RoundingMode]
allRoundingModes = [minBound .. maxBound]

-- | The SMT-LIB short name of a rounding mode.
rmName :: RoundingMode -> Text
rmName = \case
  RNE -> "RNE"
  RNA -> "RNA"
  RTP -> "RTP"
  RTN -> "RTN"
  RTZ -> "RTZ"

-- | A decoded floating-point value. The flag is the sign (True for
-- negative); finite magnitudes are positive.
data FP
  = NaN
    -- ^ Not a number (SMT-LIB has a single NaN).
  | Inf Bool
    -- ^ An infinity of the given sign.
  | Zero Bool
    -- ^ A zero of the given sign.
  | Finite Bool Rational
    -- ^ A nonzero finite value: sign and (positive) magnitude.
  deriving (Eq, Show)

-- | Total bit width @eb + sb@ of the format @(eb, sb)@.
fpWidth :: Int -> Int -> Int
fpWidth eb sb = eb + sb

-- | Exponent bias @2^(eb-1) - 1@ for an exponent width @eb@.
fpBias :: Int -> Integer
fpBias eb = 2 ^ (eb - 1) - 1

-- | Smallest normal exponent and largest exponent.
eMin, eMax :: Int -> Integer
eMin eb = 1 - fpBias eb
eMax eb = fpBias eb

-- | Largest finite magnitude.
maxFinite :: Int -> Int -> Rational
maxFinite eb sb = fromInteger (2 ^ sb - 1) * pow2 (eMax eb - fromIntegral (sb - 1))

pow2 :: Integer -> Rational
pow2 k
  | k >= 0 = fromInteger (2 ^ k)
  | otherwise = 1 % (2 ^ negate k)

-- | The canonical NaN: positive, all-ones exponent, quiet bit set.
canonicalNaN :: Int -> Int -> Integer
canonicalNaN eb sb = ((2 ^ eb - 1) `shiftL` (sb - 1)) .|. (1 `shiftL` (sb - 2))

-- | Whether a bit pattern of the format @(eb, sb)@ is any NaN.
isNaNBits :: Int -> Int -> Integer -> Bool
isNaNBits eb sb bits = case decode eb sb bits of
  NaN -> True
  _ -> False

-- | Replace any NaN pattern by 'canonicalNaN'; other patterns are
-- unchanged.
canonicalize :: Int -> Int -> Integer -> Integer
canonicalize eb sb bits
  | isNaNBits eb sb bits = canonicalNaN eb sb
  | otherwise = bits

-- | The value of the @fp@ constructor: sign bit, biased exponent and
-- trailing significand.
fpFromFields :: Int -> Int -> Integer -> Integer -> Integer -> Integer
fpFromFields eb sb s e f =
  canonicalize eb sb ((s `shiftL` (eb + sb - 1)) .|. (e `shiftL` (sb - 1)) .|. f)

-- | Decode a bit pattern of the format @(eb, sb)@ (every NaN pattern
-- decodes to 'NaN').
decode :: Int -> Int -> Integer -> FP
decode eb sb bits
  | e == 2 ^ eb - 1 = if f == 0 then Inf s else NaN
  | e == 0 = if f == 0 then Zero s else Finite s (fromInteger f * pow2 (eMin eb - q))
  | otherwise = Finite s (fromInteger (2 ^ (sb - 1) + f) * pow2 (e - fpBias eb - q))
  where
    s = testBit bits (eb + sb - 1)
    e = (bits `shiftR` (sb - 1)) .&. (2 ^ eb - 1)
    f = bits .&. (2 ^ (sb - 1) - 1)
    q = fromIntegral (sb - 1)

-- | The bit pattern of a value. Finite magnitudes must be representable.
encode :: Int -> Int -> FP -> Integer
encode eb sb = \case
  NaN -> canonicalNaN eb sb
  Inf s -> signBit s .|. ((2 ^ eb - 1) `shiftL` (sb - 1))
  Zero s -> signBit s
  Finite s m
    | m < pow2 (eMin eb) ->
        -- Subnormal: exponent field zero.
        signBit s .|. exactInteger (m / pow2 (eMin eb - q))
    | otherwise ->
        let e = floorLog2 m
            sig = exactInteger (m / pow2 (e - q))
         in signBit s .|. ((e + fpBias eb) `shiftL` (sb - 1)) .|. (sig - 2 ^ (sb - 1))
  where
    signBit s = if s then 1 `shiftL` (eb + sb - 1) else 0
    q = fromIntegral (sb - 1)
    exactInteger r
      | denominator r == 1 = numerator r
      | otherwise = error "hsmt: encode: value not representable"

-- | @floorLog2 r@ for a positive rational: the @e@ with @2^e <= r < 2^(e+1)@.
floorLog2 :: Rational -> Integer
floorLog2 r = adjust (bitLength (numerator r) - bitLength (denominator r))
  where
    adjust e
      | pow2 e > r = adjust (e - 1)
      | pow2 (e + 1) <= r = adjust (e + 1)
      | otherwise = e
    bitLength :: Integer -> Integer
    bitLength n = go 0 n
      where
        go acc 0 = acc
        go acc k = go (acc + 1) (k `shiftR` 1)

-- | The real value of a finite or zero value.
fpToRational :: FP -> Maybe Rational
fpToRational = \case
  Zero _ -> Just 0
  Finite s m -> Just (if s then negate m else m)
  _ -> Nothing

-------------------------------------------------------------------------------
-- Rounding

-- | Round a non-negative magnitude to an integer, for a value of the given
-- sign.
roundToInteger :: RoundingMode -> Bool -> Rational -> Integer
roundToInteger rm neg n = case rm of
  RTZ -> fl
  RNE
    | fr > 1 % 2 -> fl + 1
    | fr < 1 % 2 -> fl
    | otherwise -> if even fl then fl else fl + 1
  RNA -> if fr >= 1 % 2 then fl + 1 else fl
  RTP -> if neg then fl else up
  RTN -> if neg then up else fl
  where
    fl = floor n
    fr = n - fromInteger fl
    up = if fr == 0 then fl else fl + 1

-- | Round a signed magnitude (positive) into the format.
roundRational :: RoundingMode -> Int -> Int -> Bool -> Rational -> FP
roundRational rm eb sb neg m
  | k == 0 = Zero neg
  | v > maxFinite eb sb = overflow
  | otherwise = Finite neg v
  where
    e = max (floorLog2 m) (eMin eb)
    quantum = pow2 (e - fromIntegral (sb - 1))
    k = roundToInteger rm neg (m / quantum)
    v = fromInteger k * quantum
    overflow = case rm of
      RNE -> Inf neg
      RNA -> Inf neg
      RTZ -> Finite neg (maxFinite eb sb)
      RTP -> if neg then Finite neg (maxFinite eb sb) else Inf neg
      RTN -> if neg then Inf neg else Finite neg (maxFinite eb sb)

-- | Round a signed rational; zero results take the given sign.
roundSigned :: RoundingMode -> Int -> Int -> Bool -> Rational -> FP
roundSigned rm eb sb zeroSign r
  | r == 0 = Zero zeroSign
  | otherwise = roundRational rm eb sb (r < 0) (abs r)

-------------------------------------------------------------------------------
-- Operations

type Fmt = (Int, Int)

lift1 :: Fmt -> (FP -> FP) -> Integer -> Integer
lift1 (eb, sb) f x = encode eb sb (f (decode eb sb x))

lift2 :: Fmt -> (FP -> FP -> FP) -> Integer -> Integer -> Integer
lift2 (eb, sb) f x y = encode eb sb (f (decode eb sb x) (decode eb sb y))

-- | @fp.abs@ and @fp.neg@: clear or flip the sign (NaN stays NaN).
fpAbs, fpNeg :: Int -> Int -> Integer -> Integer
fpAbs eb sb = lift1 (eb, sb) $ \case
  Inf _ -> Inf False
  Zero _ -> Zero False
  Finite _ m -> Finite False m
  NaN -> NaN
fpNeg eb sb = lift1 (eb, sb) $ \case
  Inf s -> Inf (not s)
  Zero s -> Zero (not s)
  Finite s m -> Finite (not s) m
  NaN -> NaN

-- | @fp.add@, @fp.sub@, @fp.mul@, @fp.div@ and @fp.rem@ on bit patterns.
-- @fp.rem@ is the IEEE remainder (quotient rounded to nearest even), which
-- is exact, so its rounding mode argument is ignored.
fpAdd, fpSub, fpMul, fpDiv, fpRem :: RoundingMode -> Int -> Int -> Integer -> Integer -> Integer
fpAdd rm eb sb = lift2 (eb, sb) (addFP rm eb sb)
fpSub rm eb sb x y = fpAdd rm eb sb x (fpNeg eb sb y)
fpMul rm eb sb = lift2 (eb, sb) $ \a b -> case (a, b) of
  (NaN, _) -> NaN
  (_, NaN) -> NaN
  (Inf _, Zero _) -> NaN
  (Zero _, Inf _) -> NaN
  (Inf s, _) -> Inf (s /= signOf b)
  (_, Inf s) -> Inf (s /= signOf a)
  (Zero s, _) -> Zero (s /= signOf b)
  (_, Zero s) -> Zero (s /= signOf a)
  (Finite s m, Finite t n) -> roundRational rm eb sb (s /= t) (m * n)
fpDiv rm eb sb = lift2 (eb, sb) $ \a b -> case (a, b) of
  (NaN, _) -> NaN
  (_, NaN) -> NaN
  (Inf _, Inf _) -> NaN
  (Zero _, Zero _) -> NaN
  (Inf s, _) -> Inf (s /= signOf b)
  (_, Inf s) -> Zero (s /= signOf a)
  (_, Zero s) -> Inf (s /= signOf a)
  (Zero s, _) -> Zero (s /= signOf b)
  (Finite s m, Finite t n) -> roundRational rm eb sb (s /= t) (m / n)
fpRem _ eb sb = lift2 (eb, sb) $ \a b -> case (a, b) of
  (NaN, _) -> NaN
  (_, NaN) -> NaN
  (Inf _, _) -> NaN
  (_, Zero _) -> NaN
  (_, Inf _) -> a
  (Zero _, _) -> a
  (Finite s m, Finite t n) ->
    let x = if s then negate m else m
        y = if t then negate n else n
        q = x / y
        k = roundToInteger RNE (q < 0) (abs q)
        r = x - y * fromInteger (if q < 0 then negate k else k)
     in -- The remainder is exact; a zero remainder has the sign of x.
        roundSigned RNE eb sb s r

signOf :: FP -> Bool
signOf = \case
  Inf s -> s
  Zero s -> s
  Finite s _ -> s
  NaN -> False

addFP :: RoundingMode -> Int -> Int -> FP -> FP -> FP
addFP rm eb sb a b = case (a, b) of
  (NaN, _) -> NaN
  (_, NaN) -> NaN
  (Inf s, Inf t) -> if s == t then Inf s else NaN
  (Inf s, _) -> Inf s
  (_, Inf t) -> Inf t
  (Zero s, Zero t) -> Zero (if s == t then s else rm == RTN)
  (Zero _, _) -> b
  (_, Zero _) -> a
  _ -> case (fpToRational a, fpToRational b) of
    (Just x, Just y) -> roundSigned rm eb sb (rm == RTN) (x + y)
    _ -> error "unreachable"

-- | @fp.fma@: fused multiply-add @x * y + z@ with a single rounding.
fpFma :: RoundingMode -> Int -> Int -> Integer -> Integer -> Integer -> Integer
fpFma rm eb sb x y z = encode eb sb $ case (decode eb sb x, decode eb sb y, decode eb sb z) of
  (NaN, _, _) -> NaN
  (_, NaN, _) -> NaN
  (_, _, NaN) -> NaN
  (Inf _, Zero _, _) -> NaN
  (Zero _, Inf _, _) -> NaN
  (a, b, c)
    | isInf a || isInf b ->
        let ps = signOf a /= signOf b
         in case c of
              Inf t | t /= ps -> NaN
              _ -> Inf ps
    | isInf c -> c
    | otherwise ->
        let ps = signOf a /= signOf b
            p = maybe 0 id ((*) <$> fpToRational a <*> fpToRational b)
         in case (p == 0, c) of
              (True, Zero t) -> Zero (if ps == t then t else rm == RTN)
              (True, _) -> c
              (False, Zero _) -> roundSigned rm eb sb ps p
              (False, _) -> roundSigned rm eb sb (rm == RTN) (p + maybe 0 id (fpToRational c))
  where
    isInf = \case
      Inf _ -> True
      _ -> False

-- | @fp.sqrt@: correctly rounded square root (NaN for negative operands;
-- @-0@ maps to @-0@).
fpSqrt :: RoundingMode -> Int -> Int -> Integer -> Integer
fpSqrt rm eb sb = lift1 (eb, sb) $ \case
  NaN -> NaN
  Zero s -> Zero s
  Inf False -> Inf False
  Inf True -> NaN
  Finite True _ -> NaN
  Finite False m ->
    -- m = mi * 2^e with an even e; the root of mi * 4^k is computed with
    -- enough bits (k > sb + 2) that replacing an inexact root by the
    -- midpoint of its integer interval does not change the rounding.
    let e0 = negate (floorLog2' (denominator m))
        mi0 = numerator m
        (mi, e) = if odd e0 then (2 * mi0, e0 - 1) else (mi0, e0)
        k = fromIntegral sb + 3
        big = mi * 4 ^ k
        r = isqrt big
        root = if r * r == big then fromInteger r else fromInteger r + 1 % 2
     in roundRational rm eb sb False (root * pow2 (e `div` 2 - k))
  where
    -- Denominators of finite values are powers of two.
    floorLog2' d = floorLog2 (fromInteger d)

-- | Integer square root (floor).
isqrt :: Integer -> Integer
isqrt 0 = 0
isqrt n = go n
  where
    go x =
      let y = (x + n `div` x) `div` 2
       in if y >= x then x else go y

-- | @fp.roundToIntegral@: round to an integral value in the same format,
-- keeping the sign of zero results.
fpRoundToIntegral :: RoundingMode -> Int -> Int -> Integer -> Integer
fpRoundToIntegral rm eb sb = lift1 (eb, sb) $ \case
  Finite s m ->
    let k = roundToInteger rm s m
     in if k == 0 then Zero s else Finite s (fromInteger k)
  v -> v

-- | @fp.min@ and @fp.max@; zeros of different signs are unspecified.
fpMin, fpMax :: Int -> Int -> Integer -> Integer -> Maybe Integer
fpMin eb sb = minMax eb sb True
fpMax eb sb = minMax eb sb False

minMax :: Int -> Int -> Bool -> Integer -> Integer -> Maybe Integer
minMax eb sb isMin x y = case (decode eb sb x, decode eb sb y) of
  (NaN, _) -> Just y
  (_, NaN) -> Just x
  (Zero s, Zero t) | s /= t -> Nothing
  (a, b)
    | isMin -> Just (if fpLess b a then y else x)
    | otherwise -> Just (if fpLess a b then y else x)

-- | Strict order on non-NaN values (zeros are equal).
fpLess :: FP -> FP -> Bool
fpLess a b = case (ext a, ext b) of
  (Just u, Just v) -> u < v
  _ -> False
  where
    ext :: FP -> Maybe (Int, Rational)
    ext = \case
      NaN -> Nothing
      Inf s -> Just (if s then -1 else 1, 0)
      v -> (,) 0 <$> fpToRational v

-- | @fp.leq@, @fp.lt@ and @fp.eq@: IEEE comparisons (false whenever an
-- operand is NaN; zeros of either sign are equal).
fpLeq, fpLt, fpEq :: Int -> Int -> Integer -> Integer -> Bool
fpLt eb sb x y = fpLess (decode eb sb x) (decode eb sb y)
fpEq eb sb x y = case (decode eb sb x, decode eb sb y) of
  (NaN, _) -> False
  (_, NaN) -> False
  (a, b) -> not (fpLess a b) && not (fpLess b a)
fpLeq eb sb x y = fpLt eb sb x y || fpEq eb sb x y

-- | @fp.isNormal@ and @fp.isSubnormal@ (both false for zeros, infinities
-- and NaN).
fpIsNormal, fpIsSubnormal :: Int -> Int -> Integer -> Bool
fpIsNormal eb sb x = case decode eb sb x of
  Finite _ m -> m >= pow2 (eMin eb)
  _ -> False
fpIsSubnormal eb sb x = case decode eb sb x of
  Finite _ m -> m < pow2 (eMin eb)
  _ -> False

-- | Conversion between formats.
fpConvert :: RoundingMode -> (Int, Int) -> (Int, Int) -> Integer -> Integer
fpConvert rm (eb, sb) (eb', sb') x = encode eb' sb' $ case decode eb sb x of
  Finite s m -> roundRational rm eb' sb' s m
  v -> v

-- | Conversion from an integer (signed or unsigned bit-vector value).
fpFromInteger :: RoundingMode -> Int -> Int -> Integer -> Integer
fpFromInteger rm eb sb n = encode eb sb (roundSigned rm eb sb False (fromInteger n))

-- | Conversion to an integer in the given (inclusive) range; unspecified
-- for NaN, infinities and out of range values.
fpToInteger :: RoundingMode -> Int -> Int -> (Integer, Integer) -> Integer -> Maybe Integer
fpToInteger rm eb sb (lo, hi) x = case decode eb sb x of
  Zero _ -> Just 0
  Finite s m ->
    let k = roundToInteger rm s m
        v = if s then negate k else k
     in if lo <= v && v <= hi then Just v else Nothing
  _ -> Nothing