Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taylor series via F#

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?

like image 866
Dmytro Zhluktenko Avatar asked Mar 28 '17 18:03

Dmytro Zhluktenko


People also ask

What is FX in Taylor series?

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!

What is formula for Taylor's series method?

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 !

Can you use Taylor series on any function?

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 < ∞.


1 Answers

The code doesn't compile, because:

  • You're trying to divide an integer pow x n by a float. Division has to have operands of the same type.
  • You're specifying the terminal case of the wrong type. Literal 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.

like image 66
Fyodor Soikin Avatar answered Sep 18 '22 11:09

Fyodor Soikin