Advertisement
Guest User

Untitled

a guest
May 13th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (*Recursive Trapezium Rule using functional concepts*)
  2. (*Here is demonstrating the construction of a function to approximate the integral of an (R->R) function in [a,b]
  3.   by means of the trapezium rule*)
  4. (*This is done by first taking the mathematical definition, then abstracting to get an ML definition*)
  5. (*Let statements are then used to hold functions that will later on be curried to build the function*)
  6.  
  7. (*I like this because it uses map and fold for good reasons to complete the task.
  8.   And I learned a bit about local vs let and how to chain results together efficiently*)
  9.  
  10. (*Mathematical def -> ML def*)
  11. trap f (a,b) n
  12. = h/2*(f(a) + 2f(a+h) + 2f(a+2*h) + .. + f(b))
  13. = h/2 * (foldr (op +) [f(a), 2f(a+h), 2f(a+2h) .. , f(b)])
  14. = h/2 * (foldr (op +) f(a)::(map (fn x => 2*x) [f(a+h), f(a+2h), .. , f(a+(n-1)h)])::f(b)::[]
  15. = h/2 * (foldr (op +) f(a)::(map (fn x => 2*x) (map f [a+h, a+2h, ..., a+(n-1)h])::f(b)::[]
  16. = h/2 * (foldr (op +) f(a)::(map (fn x => 2*x) (map f (map (fn i => a+i*h) [1, 2, .., (n-1)])::f(b)::[]
  17. = h/2 * (foldr (op +) f(a)::(map (fn x => 2*x) (map f (map (fn i => a+i*h) (list_gen (1,n-1))))::f(b)::[]
  18.  
  19. (*Building of function*)
  20. fun list_gen (a, b) = if (a = b) then b::[]
  21.               else a::list_gen ((a+1), b);
  22.  
  23. fun trap f (a,b) n =
  24. let val h = (b-a)/real(n)
  25.     val quad_indexes = list_gen
  26.     val quad_points = map (fn i => a+real(i)*h)
  27.     val quad_vals = map f
  28.     val double = map (fn x => 2.0*x)
  29.     val sum = foldr (op+) 0.0
  30. in
  31.     (h/2.0)*(sum ((f a)::(double (quad_vals (quad_points (list_gen (1, n-1)))))@[f b]))
  32. end;
  33.  
  34.  
  35. (*This could possibly be done in one handwritten recursive function, let's try*)
  36. (*Attempt at "all in one" definition*)
  37. fun trap f (a,b) n =
  38.     let fun trap_helper (a,b) h =
  39.         if (a=b) then (f a) + (f b)
  40.         else 2.0*(f a) + (trap_helper f (a+h, b) h)
  41.     in
  42.         ((b-a)/(2.0*n)) * (trap_helper (a,b) ((b-a)/(2.0*n)))
  43.     end
  44.  
  45. (*This does not work as reals are not equality types and therefore cannot be compared*)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement