Search code examples
f#functional-programmingtaylor-series

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?


Solution

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