packages feed

papa-0.7.0: src/Papa/Base/Data/RealFrac.hs

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall #-}

-- | Total conversions from fractional types, and between floating types.
--
-- The 'RealFrac' methods of "Prelude" (@truncate@, @round@, @ceiling@,
-- @floor@, @properFraction@), its 'Real' method @toRational@, and
-- @realToFrac@, and "Data.Ratio"'s @approxRational@, are in
-- "Papa.Unsafe.Numeric": at 'Double' and 'Float' they
-- return an arbitrary number for @NaN@ and the infinities
-- (@truncate nan :: Integer@ has 309 digits), and the
-- 'RealFrac' methods wrap around where the result does not fit in the target
-- type (@truncate (300.5 :: Double) :: Word8@ is @44@). @realToFrac@ goes
-- through 'Rational', which has no @NaN@ or infinity, so at
-- @Double -> Double@ it turns @NaN@ into a number, depending on optimisation.
--
-- The functions here are total:
--
-- * 'truncateMaybe', 'roundMaybe', 'ceilingMaybe', 'floorMaybe',
--   'properFractionMaybe', 'toRationalMaybe' and 'approxRationalMaybe' are 'Data.Maybe.Nothing' for @NaN@, the
--   infinities, and (except 'toRationalMaybe') a result that does not fit in
--   the target type;
-- * 'floatToDouble' (exact) and 'doubleToFloat' (rounding) convert between
--   'Float' and 'Double' directly, so that @NaN@, the infinities and @-0@ are
--   kept;
-- * 'integralToFloating' converts an integral value to a floating type,
--   rounding where it has more digits than the floating type holds; it does not
--   wrap or throw (a value beyond the range of the floating type is an
--   infinity).
--
-- A value is finite when it equals itself (@NaN@ does not) and is zero or
-- differs from its double (an infinity is its own double). This needs no
-- 'RealFloat', so the functions work at 'Rational' and "Data.Fixed" as well.
-- At a 'Data.Ratio.Ratio' of a bounded type, whose arithmetic wraps around,
-- the results are those of its arithmetic.
--
-- @since 0.7.0
module Papa.Base.Data.RealFrac (
  truncateMaybe,
  roundMaybe,
  ceilingMaybe,
  floorMaybe,
  properFractionMaybe,
  toRationalMaybe,
  approxRationalMaybe,
  floatToDouble,
  doubleToFloat,
  integralToFloating,
) where

import Control.Monad (guard)
import Data.Bits (Bits (bitSizeMaybe, isSigned, shiftL), toIntegralSized)
import Data.Bool (Bool, bool, (&&), (||))
import Data.Eq (Eq ((/=), (==)))
import Data.Functor (fmap, ($>))
import Data.Maybe (Maybe (Just), maybe)
import Data.Ord (Ord ((<), (<=)))
import Data.Ratio (approxRational)
import GHC.Float (double2Float, float2Double)
import Prelude (Double, Float, Integer, Integral, Num ((*)), Rational, Real, RealFloat, RealFrac)
import qualified Prelude as P

-- $setup
-- >>> :set -XNoImplicitPrelude
-- >>> import Papa
-- >>> import qualified Papa.Unsafe.Numeric as U
-- >>> import Hedgehog
-- >>> import qualified Hedgehog.Gen as Gen
-- >>> import qualified Hedgehog.Range as Range
-- >>> let nan = 0 U./ 0 :: Double
-- >>> let inf = 1 U./ 0 :: Double
-- >>> let genDouble = Gen.double (Range.exponentialFloatFrom 0 (-1e30) 1e30)

-- | Whether a value is finite: not @NaN@ (which differs from itself), and
-- zero or different from its double (an infinity is its own double).
-- Doubling is exact, or overflows to an infinity, at every finite
-- floating-point value, subnormals included; it is exact at 'Rational' and
-- "Data.Fixed".
finite :: (Real a) => a -> Bool
finite x =
  x == x && (x == 0 || x * 2 /= x)
{-# INLINE finite #-}

-- | The integral part of a value by a rounding function of "Prelude",
-- given at 'Integer' and at the target type: 'Data.Maybe.Nothing' for a value that is
-- not finite or whose integral part does not fit in the target type.
--
-- A value well inside the range of a bounded target type (less than a
-- quarter of it from zero, for a signed type; less than half of its maximum,
-- for an unsigned one) is converted directly, which at 'Double' and 'Float' to
-- 'Data.Int.Int' and the other machine types is one machine instruction; its integral
-- part fits, whichever way it rounds. Every other value goes through
-- 'Integer' and 'toIntegralSized', which is exact. @NaN@ is never well inside
-- a range, so the fast path needs no test for it.
integralPart :: forall a b. (RealFrac a, Integral b, Bits b) => (a -> Integer) -> (a -> b) -> a -> Maybe b
integralPart toInteger toTarget x =
  maybe exact fast (bitSizeMaybe (0 :: b))
 where
  exact =
    guard (finite x) P.*> toIntegralSized (toInteger x)
  fast n =
    bool exact (Just (toTarget x)) (bool (0 <= x && x < power (n P.- 1)) (P.abs x < power (n P.- 2)) (isSigned (0 :: b)))
  power k =
    P.fromInteger (shiftL 1 k)
{-# INLINE integralPart #-}

-- | Total @truncate@: the integral part, rounded toward zero; 'Data.Maybe.Nothing' for @NaN@, the infinities, and a result
-- that does not fit in the target type. "Prelude"'s @truncate@ is in
-- "Papa.Unsafe.Numeric".
--
-- ==== __Examples__
--
-- >>> truncateMaybe (-2.5 :: Double) :: Maybe Int
-- Just (-2)
--
-- >>> truncateMaybe (2.5 :: Double) :: Maybe Int
-- Just 2
--
-- >>> truncateMaybe nan :: Maybe Integer
-- Nothing
--
-- >>> truncateMaybe (negate inf) :: Maybe Integer
-- Nothing
--
-- >>> truncateMaybe (300.5 :: Double) :: Maybe Word8
-- Nothing
--
-- >>> truncateMaybe (3.5 :: Rational) :: Maybe U.Natural
-- Just 3
--
-- >>> check $ withTests 200 $ property $ do x <- forAll genDouble; truncateMaybe x === (toIntegralSized (U.truncate x :: Integer) :: Maybe Int)
-- ...passed 200 tests.
-- True
--
-- @since 0.7.0
truncateMaybe :: (RealFrac a, Integral b, Bits b) => a -> Maybe b
truncateMaybe =
  integralPart P.truncate P.truncate
{-# INLINE truncateMaybe #-}

-- | Total @round@: the nearest integer, and the even one of two equally near; 'Data.Maybe.Nothing' for @NaN@, the infinities, and a result
-- that does not fit in the target type. "Prelude"'s @round@ is in
-- "Papa.Unsafe.Numeric".
--
-- ==== __Examples__
--
-- >>> roundMaybe (-2.5 :: Double) :: Maybe Int
-- Just (-2)
--
-- >>> roundMaybe (2.5 :: Double) :: Maybe Int
-- Just 2
--
-- >>> roundMaybe nan :: Maybe Integer
-- Nothing
--
-- >>> roundMaybe (negate inf) :: Maybe Integer
-- Nothing
--
-- >>> roundMaybe (300.5 :: Double) :: Maybe Word8
-- Nothing
--
-- >>> roundMaybe (3.5 :: Rational) :: Maybe U.Natural
-- Just 4
--
-- >>> check $ withTests 200 $ property $ do x <- forAll genDouble; roundMaybe x === (toIntegralSized (U.round x :: Integer) :: Maybe Int)
-- ...passed 200 tests.
-- True
--
-- @since 0.7.0
roundMaybe :: (RealFrac a, Integral b, Bits b) => a -> Maybe b
roundMaybe =
  integralPart P.round P.round
{-# INLINE roundMaybe #-}

-- | Total @ceiling@: the least integer not less than the value; 'Data.Maybe.Nothing' for @NaN@, the infinities, and a result
-- that does not fit in the target type. "Prelude"'s @ceiling@ is in
-- "Papa.Unsafe.Numeric".
--
-- ==== __Examples__
--
-- >>> ceilingMaybe (-2.5 :: Double) :: Maybe Int
-- Just (-2)
--
-- >>> ceilingMaybe (2.5 :: Double) :: Maybe Int
-- Just 3
--
-- >>> ceilingMaybe nan :: Maybe Integer
-- Nothing
--
-- >>> ceilingMaybe (negate inf) :: Maybe Integer
-- Nothing
--
-- >>> ceilingMaybe (300.5 :: Double) :: Maybe Word8
-- Nothing
--
-- >>> ceilingMaybe (3.5 :: Rational) :: Maybe U.Natural
-- Just 4
--
-- >>> check $ withTests 200 $ property $ do x <- forAll genDouble; ceilingMaybe x === (toIntegralSized (U.ceiling x :: Integer) :: Maybe Int)
-- ...passed 200 tests.
-- True
--
-- @since 0.7.0
ceilingMaybe :: (RealFrac a, Integral b, Bits b) => a -> Maybe b
ceilingMaybe =
  integralPart P.ceiling P.ceiling
{-# INLINE ceilingMaybe #-}

-- | Total @floor@: the greatest integer not greater than the value; 'Data.Maybe.Nothing' for @NaN@, the infinities, and a result
-- that does not fit in the target type. "Prelude"'s @floor@ is in
-- "Papa.Unsafe.Numeric".
--
-- ==== __Examples__
--
-- >>> floorMaybe (-2.5 :: Double) :: Maybe Int
-- Just (-3)
--
-- >>> floorMaybe (2.5 :: Double) :: Maybe Int
-- Just 2
--
-- >>> floorMaybe nan :: Maybe Integer
-- Nothing
--
-- >>> floorMaybe (negate inf) :: Maybe Integer
-- Nothing
--
-- >>> floorMaybe (300.5 :: Double) :: Maybe Word8
-- Nothing
--
-- >>> floorMaybe (3.5 :: Rational) :: Maybe U.Natural
-- Just 3
--
-- >>> check $ withTests 200 $ property $ do x <- forAll genDouble; floorMaybe x === (toIntegralSized (U.floor x :: Integer) :: Maybe Int)
-- ...passed 200 tests.
-- True
--
-- @since 0.7.0
floorMaybe :: (RealFrac a, Integral b, Bits b) => a -> Maybe b
floorMaybe =
  integralPart P.floor P.floor
{-# INLINE floorMaybe #-}

-- | Total @properFraction@: the integral part (rounded toward zero) and the
-- fractional part, with the sign of the value; 'Data.Maybe.Nothing' for @NaN@, the
-- infinities, and an integral part that does not fit in the target type.
-- "Prelude"'s @properFraction@ is in "Papa.Unsafe.Numeric".
--
-- ==== __Examples__
--
-- >>> properFractionMaybe (-3.75 :: Double) :: Maybe (Int, Double)
-- Just (-3,-0.75)
--
-- >>> properFractionMaybe nan :: Maybe (Integer, Double)
-- Nothing
--
-- >>> properFractionMaybe (300.5 :: Double) :: Maybe (Word8, Double)
-- Nothing
--
-- >>> check $ withTests 200 $ property $ do x <- forAll genDouble; fmap (toInteger . fst) (properFractionMaybe x :: Maybe (Int, Double)) === fmap toInteger (truncateMaybe x :: Maybe Int)
-- ...passed 200 tests.
-- True
--
-- @since 0.7.0
properFractionMaybe :: (RealFrac a, Integral b, Bits b) => a -> Maybe (b, a)
properFractionMaybe x =
  fmap (\n -> (n, x P.- P.fromIntegral n)) (truncateMaybe x)
{-# INLINE properFractionMaybe #-}

-- | Total @toRational@: the exact value of a finite number; 'Data.Maybe.Nothing' for
-- @NaN@ and the infinities. "Prelude"'s @toRational@ is in
-- "Papa.Unsafe.Numeric".
--
-- ==== __Examples__
--
-- >>> toRationalMaybe (0.75 :: Double)
-- Just (3 % 4)
--
-- >>> toRationalMaybe nan
-- Nothing
--
-- >>> toRationalMaybe (doubleToFloat inf)
-- Nothing
--
-- >>> toRationalMaybe (7 :: Int)
-- Just (7 % 1)
--
-- >>> check $ withTests 200 $ property $ do x <- forAll genDouble; toRationalMaybe x === Just (U.toRational x)
-- ...passed 200 tests.
-- True
--
-- @since 0.7.0
toRationalMaybe :: (Real a) => a -> Maybe Rational
toRationalMaybe x =
  guard (finite x) $> P.toRational x
{-# INLINE toRationalMaybe #-}

-- | Total @approxRational@: the simplest 'Rational' within the given distance
-- of a finite number; 'Data.Maybe.Nothing' where the number or the distance
-- is @NaN@ or an infinity, for which "Data.Ratio"'s @approxRational@, in
-- "Papa.Unsafe.Numeric", returns an arbitrary number.
--
-- ==== __Examples__
--
-- >>> approxRationalMaybe (3.14159 :: Double) 0.001
-- Just (201 % 64)
--
-- >>> approxRationalMaybe nan 0.1
-- Nothing
--
-- >>> approxRationalMaybe 0.5 inf
-- Nothing
--
-- >>> check $ withTests 200 $ property $ do x <- forAll genDouble; e <- forAll genDouble; approxRationalMaybe x e === Just (U.approxRational x e)
-- ...passed 200 tests.
-- True
--
-- @since 0.7.0
approxRationalMaybe :: (RealFrac a) => a -> a -> Maybe Rational
approxRationalMaybe x e =
  guard (finite x && finite e) $> approxRational x e
{-# INLINE approxRationalMaybe #-}

-- | A 'Float' as a 'Double', exactly: every 'Float' is a 'Double', @NaN@,
-- the infinities and @-0@ included. Use it where "Prelude" has
-- @realToFrac@, which is in "Papa.Unsafe.Numeric".
--
-- ==== __Examples__
--
-- >>> floatToDouble 0.5
-- 0.5
--
-- >>> isNaN (floatToDouble (doubleToFloat nan))
-- True
--
-- >>> floatToDouble (doubleToFloat (negate inf))
-- -Infinity
--
-- >>> isNegativeZero (floatToDouble (-0))
-- True
--
-- >>> check $ withTests 200 $ property $ do x <- forAll (Gen.float (Range.exponentialFloatFrom 0 (-1e30) 1e30)); doubleToFloat (floatToDouble x) === x
-- ...passed 200 tests.
-- True
--
-- @since 0.7.0
floatToDouble :: Float -> Double
floatToDouble =
  float2Double
{-# INLINE floatToDouble #-}

-- | A 'Double' as a 'Float', rounded to the nearest 'Float' (an infinity
-- beyond the range of 'Float'); @NaN@, the infinities and @-0@ are kept.
-- Use it where "Prelude" has @realToFrac@, which is in "Papa.Unsafe.Numeric".
--
-- ==== __Examples__
--
-- >>> doubleToFloat 0.1
-- 0.1
--
-- >>> doubleToFloat 1e300
-- Infinity
--
-- >>> isNaN (doubleToFloat nan)
-- True
--
-- >>> isNegativeZero (doubleToFloat (-0))
-- True
--
-- >>> check $ withTests 200 $ property $ do x <- forAll genDouble; doubleToFloat x === U.realToFrac x
-- ...passed 200 tests.
-- True
--
-- @since 0.7.0
doubleToFloat :: Double -> Float
doubleToFloat =
  double2Float
{-# INLINE doubleToFloat #-}

-- | An integral value in a floating type, rounded where it has more digits
-- than the floating type holds; a value beyond the range of the floating type
-- is an infinity. It does not wrap around or throw. "Prelude"'s
-- @fromIntegral@ is in "Papa.Unsafe.Numeric".
--
-- ==== __Examples__
--
-- >>> integralToFloating (3 :: Int) :: Double
-- 3.0
--
-- >>> integralToFloating (pow 2 53 + 1 :: Integer) :: Double
-- 9.007199254740992e15
--
-- >>> integralToFloating (pow 10 400 :: Integer) :: Double
-- Infinity
--
-- >>> check $ withTests 200 $ property $ do n <- forAll (Gen.int (Range.linearFrom 0 (negate (pow 2 53)) (pow 2 53))); U.truncate (integralToFloating n :: Double) === n
-- ...passed 200 tests.
-- True
--
-- @since 0.7.0
integralToFloating :: (Integral a, RealFloat b) => a -> b
integralToFloating =
  P.fromIntegral
{-# INLINE integralToFloating #-}