Haskell logbase错误

Pph*_*nix 7 haskell logarithm rounding-error

我试图使用长度等于的事实来计算Haskell中Integer的长度truncate (log10(x)+1).

使用我创建的整数:

len :: Integer -> Integer
len i = toInteger (truncate (logBase 10 (fromIntegral i)) + 1)
Run Code Online (Sandbox Code Playgroud)

不幸的是,并非所有数字都得到正确的长度.我尝试了几个不同的案例,发现:

logBase 10 10         = 1.0
logBase 10 100        = 2.0
logBase 10 1000       = 2.9999..6
logBase 10 10000      = 4.0
logBase 10 100000     = 5.0
logBase 10 1000000    = 5.9999999
Run Code Online (Sandbox Code Playgroud)

有没有理由logBase 10 1000不返回3.0?如何在基数10中获得1000的正确日志值?

Eri*_*ikR 5

GHC 模块中有一个整数对数基函数,其类型为Integer -> Integer -> Int#

用法示例:

{-# LANGUAGE MagicHash #-}

import Control.Monad
import GHC.Integer.Logarithms ( integerLogBase# )
import GHC.Exts (Int(..))

main = do
  forM_ [(1::Int)..20] $ \n -> do
    let a = 10^n-1
        la = I# (integerLogBase# 10 a)
        b = 10^n
        lb = I# (integerLogBase# 10 b)
    putStrLn $ show a ++ " -> " ++ show la
    putStrLn $ show b ++ " -> " ++ show lb
Run Code Online (Sandbox Code Playgroud)

输出:

9 -> 0
10 -> 1
99 -> 1
100 -> 2
999 -> 2
1000 -> 3
9999 -> 3
10000 -> 4
99999 -> 4
100000 -> 5
999999 -> 5
1000000 -> 6
9999999 -> 6
...
9999999999999999999 -> 18
10000000000000000000 -> 19
99999999999999999999 -> 19
100000000000000000000 -> 20
Run Code Online (Sandbox Code Playgroud)