I'm trying to write Taylor series in F#. Have a look at my code
let rec iter a b f i =
if a > b then i;
else f a (iter (a+1) b f i)
let sum a b = iter a b (+) 0 // from 0
// e^x = 1 + x + (x^2)/2 + ... (x^n)/n! + ...
let fact n = iter 1 n (*) 1 // factorial
let pow x n = iter 1 n (fun n acc -> acc * x) 1
let exp x =
iter 0 x
(fun n acc ->
acc + (pow x n) / float (fact n)) 0
In the last row I am trying cast int fact n
to float, but seems like I'm wrong because this code isn't compileable :(
Am I doing the right algorithm?
Can I call my code functional-first?
The Taylor series of a function f(x) centered at a point x=a is an infinite series of terms containing integer powers of x that represents this function on some interval. The formula for this series is given by. f(x)=∑∞n=0f(n)(a)(x−a)nn!
Taylor's Series Theorem Assume that if f(x) be a real or composite function, which is a differentiable function of a neighbourhood number that is also real or composite. Then, the Taylor series describes the following power series : f ( x ) = f ( a ) f ′ ( a ) 1 ! ( x − a ) + f ” ( a ) 2 !
No. A necessary condition for a Taylor series to be able to represent a function over a region is that the function is infinitely differentiable in that region. One function that can't be represented by a Taylor series is f(x) = IXI , -∞ < x < ∞.
The code doesn't compile, because:
pow x n
by a float. Division has to have operands of the same type.0
is integer. If you want float zero, use 0.0
or abbreviated 0.
Try this:
let exp x =
iter 0 x
(fun n acc ->
acc + float (pow x n) / float (fact n)) 0.
P.S. In the future, please provide the exact error messages and/or unexpected results that you're getting. Simply saying "doesn't work" is not a good description of a problem.
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