Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 我是如何错误地计算e^x的?_Haskell - Fatal编程技术网

Haskell 我是如何错误地计算e^x的?

Haskell 我是如何错误地计算e^x的?,haskell,Haskell,我试图用Haskell中的幂级数近似来估计e^x import Data.Function -- Take two integers and divide them and return a float as a result. -- So 1/2 would be 0.5 fd :: Int -> Int -> Double fd = (/) `on` fromIntegral -- Helper function to compute factorial fact :: In

我试图用Haskell中的幂级数近似来估计e^x

import Data.Function

-- Take two integers and divide them and return a float as a result.
-- So 1/2 would be 0.5
fd :: Int -> Int -> Double
fd = (/) `on` fromIntegral

-- Helper function to compute factorial
fact :: Int -> Int
fact 1 = 1
fact n = n * fact (n-1)

-- Calculate e^x using the power series for e^x (n is the number of
-- of terms used to approximate e^x
computeHelper :: Double -> Int -> Double -> Double
computeHelper x 0 res = res + 1
computeHelper x n res = computeHelper x (n-1) (res + (x**n `fd` (fact n)))

compute :: Double -> Int -> Double
compute x n = computeHelper x n 0.0
调用
compute15
将给出
6
。这是不正确的

fd
fact
似乎工作正常。因此,我猜问题在于
computeHelper
。但是,在Python中遵循相同的逻辑:

from math import factorial

def compute(x, n, res=0):
    if n == 0:
        return res + 1
    return compute(x, n-1, res + (x**n*1.0/(factorial(n))))

print compute(1, 5)

我得到了预期的
2.71667
,因此我不明白为什么Haskell版本不起作用。

这是一个运算符优先级问题。
fd
的优先级高于
**
。如果你加上额外的括号,你会更清楚为什么会得到6分:

(x**(n `fd` (fact n)))
解决这一问题的方法是在求幂运算周围加上括号,然后稍微调整一些内容,以便它们进行打字检查:

((x^n) / (fromIntegral (fact n)))

当正确键入时(与您的实现不同),不会泄漏空间的阶乘一行是
fact n=product[1..n]
。但是,多行定义的速度要快得多。您还应该为0定义阶乘。0!=1.