Implement a function that calculates the value of e ^ x, x is a parameter of the function, an integer. To do this, use the Taylor series expansion to calculate the potency of e. The function will receives as a parameter, in addition to the exponent x, the number of terms of the series, which will operate as a maximum value of n. For the resolution of this function, recursion must be used.
I made this:
factorial 0 = 1
factorial n = n * factorial (n-1)
consigna3::Int->Int->Float
consigna3 _ 0 = 1
consigna3 x n = (fromIntegral(x^n) / fromIntegral(factorial n)) + consigna3 x (n-1)
But some results are wrong, this is what I expected:
Ejemplo 1: Main> funcion3 1 1
2.0
Ejemplo 2: Main> funcion3 1 10
2.718282
Ejemplo 3: Main> funcion3 2 10
7.388997
Ejemplo 4: Main> funcion3 10 20
21991.48
Ejemplo 5: Main> funcion3 10 30
22026.46
Ejemplo 6: Main> funcion3 0 30
1.0
The results (10 20) and (10 30) do not match what the function I did returns. What I am doing wrong? Thanks and sorry for my English.
You are using
Int
for calculations that will overflow anInt
. Instead, convert toFloat
right away, and then usingFloat
for everything. So:There are two critical changes from
Int
toFloat
here: first, you dox^n
wherex :: Int
, but I dofromIntegral x^n
wherefromIntegral x :: Float
; second, you dofactorial n
wheren :: Int
, but I dofactorial (fromIntegral n)
wherefromIntegral n :: Float
.