/ F#

HR F#: Evaluating eˣ

The problem Evaluating e^x:

The series expansion of eˣ is given by
$$1 + x + \frac{x^2} {2!} + \frac{x^3} {3!} + \frac{x^4} {4!} + ...$$
Evaluate eˣ for given values of x by using the above expansion for the first 10 terms.

This problem is interesting because it can be solved in a number of ways, different in performance and limits.

First of all, let's try to solve the problem in straightforward way and sum n items of the power series (or more specifically Taylor series):

let power x y =
  seq { 1..y } |> Seq.fold (fun m _ -> m * x) 1.0

let factorial x =
  seq { 1..x } |> Seq.fold (fun m v -> m * float(v)) 1.0

let sum s =
  s |> Seq.fold (fun s v -> s + v) 0.0

let ex x =
  seq { 0..9 }
  |> Seq.map (fun n -> (power x n) / (factorial n))
  |> sum

printfn "%A" (ex 2.0)

ex applies series function from 0 because x^0/0! = 1 and x^1/1! = x.

Although this solution works good enough to pass the tests, it is easy to see that it does a lot of extra work on calcuating power and factorial, although most of the job is already done while calculating previous sequence item.

The improved solution is to pass the calculated power and factorial to the next step. It changes the program significally. The power and factorial functions are no longer requried as all calculations are done in ex, which is now recursive and returns sum, power and factorial.

let rec ex x n =
  match n with
  | 0 -> (1.0, 1.0, 1.0)
  | _ -> let s, p, f = ex x (n - 1)
         let np = p * x
         let nf = f * float(n)
         (s + np / nf, np, nf)

let v, _, _ = ex 2.0 9 
printfn "%A" v
Alex Netkachov

Alex Netkachov

Alex Netkachov is a Senior Software Developer, currently working in Central London on new generation of energy trading solutions for brokers, traders and exchanges.

Read More

Why not to chat about this post? Join Telegram group Alex@Net or message on Twitter to alex_at_net. Alternatively, use the comments form below.