Haskell日志库错误 [英] Haskell logbase error
本文介绍了Haskell日志库错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图计算Haskell中Integer的长度,使用长度等于 truncate(log10(x)+1)
的事实。 p>
使用我创建的整数:
len :: Integer - >整数
len i = toInteger(truncate(logBase 10(fromIntegral i))+ 1)
不幸的是,并非所有的数字都得到正确的长度。我试了几个不同的案例,发现:
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
为什么 logBase 10 1000
不返回3.0?如何以10为基数获得1000的正确对数值?
解决方案
GHC模块中有一个整数对数基函数其中键入
整数 - >整数 - > { - #LANGUAGE MagicHash# - }
import Control.Monad
import GHC.Integer.Logarithms(integerLogBase#)
import GHC.Exts(Int(..) )
main = do
forM_ [(1 :: Int).. 20] $ \\\
- >做
让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
输出:
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
I am trying to calculate the length of an Integer in Haskell, using the fact that the length is equal to truncate (log10(x)+1)
.
Using Integers I created:
len :: Integer -> Integer
len i = toInteger (truncate (logBase 10 (fromIntegral i)) + 1)
Unfortunately, not all numbers get the correct length. I tried a few different cases and found that:
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
Is there a reason why logBase 10 1000
doesn't return 3.0? How do I get the correct log-value for 1000 in base 10?
解决方案 There is an integer log base function in GHC modules which has type Integer -> Integer -> Int#
.
Example usage:
{-# 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
Output:
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
这篇关于Haskell日志库错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文