Advertisement
Gumanitariy

Taylor

Nov 13th, 2017
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.46 KB | None | 0 0
  1. // Kolosova Alexandra
  2. // variant #5
  3.  
  4. let a = 0.0
  5. let b = 0.5
  6. let n = 10
  7. let eps = 0.00000001
  8.  
  9. let iter f i a b =
  10.     let rec iter' a acc =
  11.        if a > b then acc
  12.        else iter' (a+1) (f a acc)
  13.     iter' a i
  14.  
  15. // exponentiation
  16. //let power x = iter (fun _ acc -> acc * x) 1. 1
  17.  
  18. // 2 * ( cos^2 (x) - 1 )
  19.  
  20. //let f (x:float) = cos >> power 2 >> (-) 1. >> (*) 2.
  21. //let f x = 2. * ((power (cos(x)) 2) - 1.)
  22. let f (x:float) = 2. * (float(cos(x)**2.) - 1.)
  23.  
  24. // (-1)^n * (2x)^2n / ((2n)!)
  25.  
  26. let fact =
  27.    let rec fact' acc = function
  28.        | 1 -> acc
  29.        | n -> fact' (acc*n) (n-1)
  30.    fact' 1
  31.  
  32.  
  33. // calculate i element
  34. //let taylorElement x i = (0. - power x n)* power (2.*x) (2 * n) / float((fact(2*n) ))
  35. let taylorElement (x:float) n = (-1.0)**float(n) * (float (2.*x)**float (2*n)) / float(fact(2*n))
  36.  
  37. // Taylor series in "dumb" way:
  38. let taylorNaive x = iter (fun n acc -> acc + ((-1.)** float n) * (2. * x)**(2. * float n) / float((fact(2*n) ))) 0. 0 n
  39. //let taylorNaive x = iter (fun n acc -> acc + taylorElement x n) 0. 0 n
  40.  
  41. // Taylor series in a more efficient way
  42. let taylor (x:float) =
  43.     let rec loop prev i acc =
  44.         if (abs(taylorElement x i ) < eps) then acc
  45.         else loop (taylorElement x i) (i + 1) (acc + taylorElement x i)
  46.     loop (-2.*x*x) 1 0.
  47.  
  48.  
  49. let main =
  50.   for i=0 to n do
  51.     let x = a + (float i) / (float n) * (b - a)
  52.     printfn "%5.2f  %10.6f  %10.6f   %10.6f" x (f x) (taylorNaive x) (taylor x)
  53.  
  54. main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement