Taylor series through F #

I am trying to write a Taylor series in F #. See my code

let rec iter abfi = if a > b then i; else fa (iter (a+1) bfi) let sum ab = iter ab (+) 0 // from 0 // e^x = 1 + x + (x^2)/2 + ... (x^n)/n! + ... let fact n = iter 1 n (*) 1 // factorial let pow xn = iter 1 n (fun n acc -> acc * x) 1 let exp x = iter 0 x (fun n acc -> acc + (pow xn) / float (fact n)) 0 

On the last line, I'm trying to use int fact n for a float, but it looks like I'm wrong because this code is not compiling :( Am I doing the right algorithm?

Can I name my code first?

+5
source share
1 answer

The code does not compile because:

  • You are trying to split the integer pow xn by a float. A department must have operands of the same type.
  • You specify the wrong terminal type. Literal 0 is an integer. If you want to use float zero, use 0.0 or the abbreviated 0.

Try the following:

 let exp x = iter 0 x (fun n acc -> acc + float (pow xn) / float (fact n)) 0. 

PS In the future, indicate the exact error messages and / or unexpected results you get. Just saying β€œnot working” is not a good description of the problem.

+6
source

Source: https://habr.com/ru/post/1266035/


All Articles