Haskell 我是如何错误地计算e^x的?
我试图用Haskell中的幂级数近似来估计e^xHaskell 我是如何错误地计算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
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.