So I'm trying to do some number theory work, and I was using Mathematica but thought that Haskell would be more suited to dealing with infinite lists (as AFAIK Mathematica doesn't have lazy evaluation). What I want to do is have Haskell store all the digits of 1/x in an infinite lazy list. So far my searching has not turned up a way to split a ratio into its digits that returns a list of digits rather than an actual floating point number.
问问题
269 次
2 回答
6
我们也可以将其实现为一个简单的流生产者:
divDigits :: Int -> Int -> [Int]
divDigits x y = x `div` y : divDigits (10 * (x `mod` y)) y
实际上有这种使用惰性列表的“无限”精度数字表示的库,请参阅Haskell Wiki。
于 2014-01-15T15:34:01.537 回答
2
非常感谢 Sam Yonnou,他提供的链接有正确
的公式使用的公式:
x/y 的第 n 位是 (10^(n-1)*x mod y)/y = floor(10 * (10^(n-1)*x mod y) / y) mod 10
结束代码如下所示:
nDigRat :: Int -> Int -> Int -> Int
nDigRat num denom n = floor (fromIntegral (10*(10^(n-1)*num `rem` denom)) /
fromIntegral denom)
`rem` 10
decExpansionRecipRat :: Int -> [Int]
decExpansionRecipRat n = map (nDigRat 1 n) [1..]
于 2014-01-15T06:31:35.663 回答