我试图估计e^x在Haskell中使用幂级数进行近似.
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
Run Code Online (Sandbox Code Playgroud)
打电话compute 1 5给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)
Run Code Online (Sandbox Code Playgroud)
我得到的2.71666666667是预期的,所以我很困惑为什么Haskell版本不起作用.
它是运营商优先问题.在fd具有比一个更高的优先级**.如果你添加额外的括号更清楚为什么你得到6:
(x**(n `fd` (fact n)))
Run Code Online (Sandbox Code Playgroud)
解决这个问题的方法是将括号括在指数周围,然后稍微调整一下,以便进行类型检查:
((x^n) / (fromIntegral (fact n)))
Run Code Online (Sandbox Code Playgroud)