Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How am I computing e^x incorrectly?

Tags:

haskell

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.

like image 886
Dair Avatar asked Mar 16 '23 21:03

Dair


1 Answers

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)))
like image 107
hugomg Avatar answered Mar 23 '23 14:03

hugomg