Haskell fromInteger函数负指数

时间:2018-06-25 17:15:27

标签: haskell

我是Haskell的新手,我正在尝试定义具有递归的函数eAprox :: Integer -> Float。该函数是下一个summation of 1/(k!) with k from 0 to inf

到目前为止,我得到的是

eaprox :: Integer -> Float

eaprox n | n == 0 = 1

         | n > 0 = fromInteger ((factorial n)^(-1)) + eaprox (n-1)

Haskell接受,但是用任何数字(0除外)都会给我消息 *例外:负数。我将(^^)或(**)更改为(^),但是我什至无法加载该函数。.我猜fromInteger函数存在错误,因为我不太了解它的工作原理。.有什么想法吗?

1 个答案:

答案 0 :(得分:4)

Fatorial产生一个正整数,并且该整数的倒数^(-1)(从1开始)是从0到1的一个分数;永远不会是整数。因此,在进行对等之前,您需要执行转换,例如:

factorial n = product [1..n]

eaprox n = sum [recip . fromInteger . factorial $ x | x <- [0..n]]

在此版本中,eaprox 17大约等于exp 1