I am trying to estimate e^xusing power series for approximation in 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
The challenge compute 1 5gives 6. This is not true.
Both fdand factare working properly. Therefore, I assume that the problem is related to computeHelper. However, following the same logic in 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)
I get 2.71666666667that as expected, so I'm confused why the Haskell version is not working.
source
share