haskell - How am I computing e^x incorrectly? -
i trying estimate e^x
using power series approximation in haskell.
import data.function -- take 2 integers , divide them , return float result. -- 1/2 0.5 fd :: int -> int -> double fd = (/) `on` fromintegral -- helper function compute factorial fact :: int -> int fact 1 = 1 fact n = n * fact (n-1) -- calculate e^x using power series e^x (n number of -- of terms used 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
. incorrect.
both fd
, fact
appear working fine. therefore, i'm guessing issue computehelper
. however, following 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 2.71666666667
expected, confused why haskell version doesn't work.
its operator precedence issue. fd
has higher precedence **
. if add parenthesis clearer why getting 6:
(x**(n `fd` (fact n)))
the way fix put parenthesis around exponentiation , tweak things bit typecheck:
((x^n) / (fromintegral (fact n)))
Comments
Post a Comment