Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Kolosova Alexandra
- // variant #5
- let a = 0.0
- let b = 0.5
- let n = 10
- let eps = 0.00000001
- let iter f i a b =
- let rec iter' a acc =
- if a > b then acc
- else iter' (a+1) (f a acc)
- iter' a i
- // exponentiation
- //let power x = iter (fun _ acc -> acc * x) 1. 1
- // 2 * ( cos^2 (x) - 1 )
- //let f (x:float) = cos >> power 2 >> (-) 1. >> (*) 2.
- //let f x = 2. * ((power (cos(x)) 2) - 1.)
- let f (x:float) = 2. * (float(cos(x)**2.) - 1.)
- // (-1)^n * (2x)^2n / ((2n)!)
- let fact =
- let rec fact' acc = function
- | 1 -> acc
- | n -> fact' (acc*n) (n-1)
- fact' 1
- // calculate i element
- //let taylorElement x i = (0. - power x n)* power (2.*x) (2 * n) / float((fact(2*n) ))
- let taylorElement (x:float) n = (-1.0)**float(n) * (float (2.*x)**float (2*n)) / float(fact(2*n))
- // Taylor series in "dumb" way:
- let taylorNaive x = iter (fun n acc -> acc + ((-1.)** float n) * (2. * x)**(2. * float n) / float((fact(2*n) ))) 0. 0 n
- //let taylorNaive x = iter (fun n acc -> acc + taylorElement x n) 0. 0 n
- // Taylor series in a more efficient way
- let taylor (x:float) =
- let rec loop prev i acc =
- if (abs(taylorElement x i ) < eps) then acc
- else loop (taylorElement x i) (i + 1) (acc + taylorElement x i)
- loop (-2.*x*x) 1 0.
- let main =
- for i=0 to n do
- let x = a + (float i) / (float n) * (b - a)
- printfn "%5.2f %10.6f %10.6f %10.6f" x (f x) (taylorNaive x) (taylor x)
- main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement