I am trying to estimate e^x
using the 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
Calling compute 1 5
gives 6
. Which is incorrect.
Both fd
and fact
appear to be working fine. Therefore, I'm guessing the issue is with 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.71666666667
which is as expected, so I am confused why the Haskell version doesn't work.
Its an operator precedence issue. The fd
has a higher precedence than the **
. If you add extra parenthesis its clearer why you are getting a 6:
(x**(n `fd` (fact n)))
The way to fix this would be to put parenthesis around the exponentiation and then tweak things a bit so they typecheck:
((x^n) / (fromIntegral (fact n)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With