{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE PostfixOperators #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Data.CReal.Internal
(
CReal(..)
, atPrecision
, crealPrecision
, mulBounded
, (.*.)
, mulBoundedL
, (.*)
, (*.)
, recipBounded
, shiftL
, shiftR
, square
, expBounded
, expPosNeg
, logBounded
, atanBounded
, sinBounded
, cosBounded
, crMemoize
, powerSeries
, alternateSign
, (/.)
, log2
, log10
, isqrt
, showAtPrecision
, decimalDigitsAtPrecision
, rationalToDecimal
) where
import Data.List (scanl')
import Data.Ratio (numerator,denominator,(%))
import GHC.Base (Int(..))
import GHC.Integer.Logarithms (integerLog2#, integerLogBase#)
import GHC.TypeLits
import Numeric (readSigned, readFloat)
import Data.Function.Memoize (memoize)
import System.Random (Random(..))
{-# ANN module "HLint: ignore Reduce duplication" #-}
default ()
newtype CReal (n :: Nat) = CR (Int -> Integer)
crMemoize :: (Int -> Integer) -> CReal n
crMemoize = CR . memoize
crealPrecision :: KnownNat n => CReal n -> Int
crealPrecision = fromInteger . natVal
atPrecision :: CReal n -> Int -> Integer
(CR x) `atPrecision` p = x p
instance KnownNat n => Show (CReal n) where
show x = showAtPrecision (crealPrecision x) x
instance KnownNat n => Read (CReal n) where
readsPrec _ = readSigned readFloat
instance Num (CReal n) where
{-# INLINE fromInteger #-}
fromInteger i = crMemoize (\p -> i * 2 ^ p)
{-# INLINE negate #-}
negate (CR x) = crMemoize (negate . x)
{-# INLINE abs #-}
abs (CR x) = crMemoize (abs . x)
{-# INLINE (+) #-}
CR x1 + CR x2 = crMemoize (\p -> let n1 = x1 (p + 2)
n2 = x2 (p + 2)
in (n1 + n2) /. 4)
{-# INLINE (*) #-}
CR x1 * CR x2 = crMemoize (\p -> let s1 = log2 (abs (x1 0) + 2) + 3
s2 = log2 (abs (x2 0) + 2) + 3
n1 = x1 (p + s2)
n2 = x2 (p + s1)
in (n1 * n2) /. 2^(p + s1 + s2) )
signum x = crMemoize (\p -> signum (x `atPrecision` p) * 2^p)
instance Fractional (CReal n) where
fromRational n = fromInteger (numerator n) *. recipBounded (fromInteger (denominator n))
{-# INLINE recip #-}
recip (CR x) = crMemoize (\p -> let s = findFirstMonotonic ((3 <=) . abs . x)
n = x (p + 2 * s + 2)
in 2^(2 * p + 2 * s + 2) /. n)
instance Floating (CReal n) where
pi = 4 * piBy4
exp x = let CR o = x / ln2
l = o 0
y = x - fromInteger l * ln2
in if l == 0
then expBounded x
else expBounded y `shiftL` fromInteger l
log x = let CR o = x
l = log2 (o 2) - 2
in if
| l < 0 -> - log (recip x)
| l == 0 -> logBounded x
| l > 0 -> let a = x `shiftR` l
in logBounded a + fromIntegral l *. ln2
sqrt (CR x) = crMemoize (\p -> let n = x (2 * p)
in isqrt n)
x ** y = exp (log x * y)
logBase x y = log y / log x
sin x = cos (x - pi / 2)
cos x = let CR o = x / piBy4
s = o 1 /. 2
octant = fromInteger $ s `mod` 8
offset = x - (fromIntegral s * piBy4)
fs = [ cosBounded
, negate . sinBounded . subtract piBy4
, negate . sinBounded
, negate . cosBounded . (piBy4-)
, negate . cosBounded
, sinBounded . subtract piBy4
, sinBounded
, cosBounded . (piBy4-)]
in (fs !! octant) offset
tan x = sin x .* recip (cos x)
asin x = 2 * atan (x .*. recipBounded (1 + sqrt (1 - x.*.x)))
acos x = pi/2 - asin x
atan x = let
q = x `atPrecision` 2
in if
| q < -4 -> atanBounded (negate (recipBounded x)) - pi / 2
| q == -4 -> -pi / 4 - atanBounded ((x + 1) .*. recipBounded (x - 1))
| q == 4 -> pi / 4 + atanBounded ((x - 1) .*. recipBounded (x + 1))
| q > 4 -> pi / 2 - atanBounded (recipBounded x)
| otherwise -> atanBounded x
sinh x = let (expX, expNegX) = expPosNeg x
in (expX - expNegX) / 2
cosh x = let (expX, expNegX) = expPosNeg x
in (expX + expNegX) / 2
tanh x = let e2x = exp (2 * x)
in (e2x - 1) *. recipBounded (e2x + 1)
asinh x = log (x + sqrt (x * x + 1))
acosh x = log (x + sqrt (x + 1) * sqrt (x - 1))
atanh x = (log (1 + x) - log (1 - x)) / 2
instance KnownNat n => Real (CReal n) where
toRational x = let p = crealPrecision x
in x `atPrecision` p % 2^p
instance KnownNat n => RealFrac (CReal n) where
properFraction x = let p = crealPrecision x
n = (x `atPrecision` p) `quot` 2^p
f = x - fromInteger n
in (fromInteger n, f)
instance KnownNat n => RealFloat (CReal n) where
floatRadix _ = 2
floatDigits _ = error "Data.CReal.Internal floatDigits"
floatRange _ = error "Data.CReal.Internal floatRange"
decodeFloat x = let p = crealPrecision x
in (x `atPrecision` p, -p)
encodeFloat m n = fromRational (m % 2^(-n))
exponent = error "Data.CReal.Internal exponent"
significand = error "Data.CReal.Internal significand"
scaleFloat = flip shiftL
isNaN _ = False
isInfinite _ = False
isDenormalized _ = False
isNegativeZero _ = False
isIEEE _ = False
atan2 y x = crMemoize (\p ->
let y' = y `atPrecision` p
x' = x `atPrecision` p
θ = if | x' > 0 -> atan (y/x)
| x' == 0 && y' > 0 -> pi/2
| x' < 0 && y' > 0 -> pi + atan (y/x)
| x' <= 0 && y' < 0 -> -atan2 (-y) x
| y' == 0 && x' < 0 -> pi
| x'==0 && y'==0 -> 0
| otherwise -> error "Data.CReal.Internal atan2"
in θ `atPrecision` p)
instance KnownNat n => Eq (CReal n) where
x == y = let p = crealPrecision x
in (x - y) `atPrecision` p == 0
instance KnownNat n => Ord (CReal n) where
compare x y = let p = crealPrecision x
in compare ((x - y) `atPrecision` p) 0
max (CR x) (CR y) = crMemoize (\p -> max (x p) (y p))
min (CR x) (CR y) = crMemoize (\p -> min (x p) (y p))
instance KnownNat n => Random (CReal n) where
randomR (lo, hi) g = let d = hi - lo
l = 1 + log2 (abs d `atPrecision` 0)
p = l + crealPrecision lo
(n, g') = randomR (0, 2^p) g
r = fromRational (n % 2^p)
in (r * d + lo, g')
random g = let p = 1 + crealPrecision (undefined :: CReal n)
(n, g') = randomR (0, max 0 (2^p - 2)) g
r = fromRational (n % 2^p)
in (r, g')
piBy4 :: CReal n
piBy4 = 4 * atanBounded (recipBounded 5) - atanBounded (recipBounded 239)
ln2 :: CReal n
ln2 = logBounded 2
infixl 7 `mulBounded`, `mulBoundedL`, .*, *., .*.
(.*) :: CReal n -> CReal n -> CReal n
(.*) = mulBoundedL
(*.) :: CReal n -> CReal n -> CReal n
(*.) = flip mulBoundedL
(.*.) :: CReal n -> CReal n -> CReal n
(.*.) = mulBounded
mulBoundedL :: CReal n -> CReal n -> CReal n
mulBoundedL (CR x1) (CR x2) = crMemoize (\p -> let s1 = 4
s2 = log2 (abs (x2 0) + 2) + 3
n1 = x1 (p + s2)
n2 = x2 (p + s1)
in (n1 * n2) /. 2^(p + s1 + s2))
mulBounded :: CReal n -> CReal n -> CReal n
mulBounded (CR x1) (CR x2) = crMemoize (\p -> let s1 = 4
s2 = 4
n1 = x1 (p + s2)
n2 = x2 (p + s1)
in (n1 * n2) /. 2^(p + s1 + s2))
recipBounded :: CReal n -> CReal n
recipBounded (CR x) = crMemoize (\p -> let s = 2
n = x (p + 2 * s + 2)
in 2^(2 * p + 2 * s + 2) /. n)
square :: CReal n -> CReal n
square (CR x) = crMemoize (\p -> let s = log2 (abs (x 0) + 2) + 3
n = x (p + s)
in (n * n) /. 2^(p + 2 * s))
expBounded :: CReal n -> CReal n
expBounded x = let q = (1%) <$> scanl' (*) 1 [1..]
in powerSeries q (max 5) x
logBounded :: CReal n -> CReal n
logBounded x = let q = [1 % n | n <- [1..]]
y = (x - 1) .* recip x
in y .* powerSeries q id y
expPosNeg :: CReal n -> (CReal n, CReal n)
expPosNeg x = let CR o = x / ln2
l = o 0
y = x - fromInteger l * ln2
in if l == 0
then (expBounded x, expBounded (-x))
else (expBounded y `shiftL` fromInteger l,
expBounded (negate y) `shiftR` fromInteger l)
sinBounded :: CReal n -> CReal n
sinBounded x = let q = alternateSign (scanl' (*) 1 [ 1 % (n*(n+1)) | n <- [2,4..]])
in x * powerSeries q (max 1) (x .*. x)
cosBounded :: CReal n -> CReal n
cosBounded x = let q = alternateSign (scanl' (*) 1 [1 % (n*(n+1)) | n <- [1,3..]])
in powerSeries q (max 1) (x .*. x)
atanBounded :: CReal n -> CReal n
atanBounded x = let q = scanl' (*) 1 [n % (n + 1) | n <- [2,4..]]
d = 1 + x .*. x
rd = recipBounded d
in (x .*. rd) .* powerSeries q (+1) (x .*. x .*. rd)
infixl 8 `shiftL`, `shiftR`
shiftR :: CReal n -> Int -> CReal n
shiftR (CR x) n = crMemoize (\p -> let p' = p - n
in if p' >= 0
then x p'
else x 0 /. 2^(-p'))
shiftL :: CReal n -> Int -> CReal n
shiftL x = shiftR x . negate
showAtPrecision :: Int -> CReal n -> String
showAtPrecision p (CR x) = let places = decimalDigitsAtPrecision p
r = x p % 2^p
in rationalToDecimal places r
decimalDigitsAtPrecision :: Int -> Int
decimalDigitsAtPrecision 0 = 0
decimalDigitsAtPrecision p = log10 (2^p) + 1
rationalToDecimal :: Int -> Rational -> String
rationalToDecimal places r = p ++ is ++ if places > 0 then "." ++ fs else ""
where r' = abs r
p = case signum r of
-1 -> "-"
_ -> ""
ds = show ((numerator r' * 10^places) /. denominator r')
l = length ds
(is, fs) = if | l <= places -> ("0", replicate (places - l) '0' ++ ds)
| otherwise -> splitAt (length ds - places) ds
infixl 7 /.
(/.) :: Integer -> Integer -> Integer
n /. d = round (n % d)
log2 :: Integer -> Int
log2 x = I# (integerLog2# x)
log10 :: Integer -> Int
log10 x = I# (integerLogBase# 10 x)
isqrt :: Integer -> Integer
isqrt x | x < 0 = error "Sqrt applied to negative Integer"
| x == 0 = 0
| otherwise = until satisfied improve initialGuess
where improve r = (r + (x `div` r)) `div` 2
satisfied r = sq r <= x && sq (r + 1) > x
initialGuess = 2 ^ (log2 x `div` 2)
sq r = r * r
findFirstMonotonic :: (Int -> Bool) -> Int
findFirstMonotonic p = binarySearch l' u'
where (l', u') = findBounds 0 1
findBounds l u = if p u then (l, u)
else findBounds u (u*2)
binarySearch l u = let m = l + ((u - l) `div` 2)
in if | l+1 == u -> l
| p m -> binarySearch l m
| otherwise -> binarySearch m u
alternateSign :: Num a => [a] -> [a]
alternateSign = zipWith ($) (cycle [id, negate])
powerSeries :: [Rational] -> (Int -> Int) -> CReal n -> CReal n
powerSeries q termsAtPrecision (CR x) = crMemoize
(\p -> let t = termsAtPrecision p
d = log2 (toInteger t) + 2
p' = p + d
p'' = p' + d
m = x p''
xs = (%1) <$> iterate (\e -> m * e /. 2^p'') (2^p')
r = sum . take (t + 1) . fmap (round . (* (2^d))) $ zipWith (*) q xs
in r /. 4^d)