Advertisement
Guest User

Renat Bashirov

a guest
Mar 6th, 2014
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.95 KB | None | 0 0
  1. //==========================PART 1(EXAMPLE 8)========================================
  2. let functionB (x : float) = 1. / (2. * x - 5.)
  3. let eps = 0.001
  4.  
  5. let rec iter f init a b =
  6.     if a <= b then f a (iter f init (a + 1) b)
  7.     else init
  8. let power x n = iter (fun z acc -> float(acc) * x) 1. 1 n
  9. let functionTaylorSeries (x : float) =
  10.     let realValue =
  11.         functionB x
  12.     let rec iterTillGotRealValue (acc : float) i =  
  13.         if (abs (realValue - acc) < eps)
  14.             then (acc,i)
  15.             else iterTillGotRealValue (acc - float(power 2. i) * float(power x i) / float(power 5. (i+1))) (i+1)
  16.     iterTillGotRealValue 0. 0
  17.  
  18. let functionTaylorSeriesFaster (x : float) =
  19.     let realValue =
  20.         functionB x
  21.     let rec iterTillGotRealValue (acc : float) (acc4Component : float) i =  
  22.         //printf "%f\n" acc
  23.         if (abs (realValue - acc) < eps)
  24.             then (acc,i)
  25.             else iterTillGotRealValue (acc - acc4Component) (acc4Component * 2. * x / 5.) (i+1)
  26.     iterTillGotRealValue 0. 0.2 0
  27.  
  28. printf "x\tПервый способ\tКол-во итераций\tВторой способ\tКол-во итераций\tЗначение функции\n"
  29. let n = 10
  30. for i = 0 to n do
  31.     let point x =
  32.         2. * float(x) / float(n)
  33.     let x =
  34.         point(i)
  35.     let res1 =  
  36.         functionTaylorSeries x  
  37.     let res2 =  
  38.         functionTaylorSeriesFaster x  
  39.     printf "%f\t%f\t%d\t%f\t%d\t%f\n" x (fst res1) (snd res1) (fst res2) (snd res2) (functionB x)
  40.  
  41.  
  42. //==========================PART 2(EXAMPLE 4)========================================
  43. let eps2 = 0.00001
  44. let myfun (x : float) =
  45.     3. * x - 14. + (exp x) - (exp (-x))
  46. let derivativeOfMyFun (x : float) =
  47.     3. + (exp x) + (exp (-x))
  48.  
  49. let rec getRoot f derivative curX =
  50.     if (abs (f curX) < eps2)
  51.         then curX
  52.         else getRoot f derivative (curX - (f curX) / (derivative curX))
  53. printf "%f\n" (getRoot myfun derivativeOfMyFun 1.)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement