Advertisement
Guest User

Untitled

a guest
Aug 28th, 2015
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. using System;
  2.  
  3. public static class Integration
  4. {
  5. /// <summary>
  6. /// Return the integral from a to b of function f
  7. /// using the left hand rule
  8. /// </summary>
  9. public static double LeftHand(double a, double b, Func<double, double> f, int strips = -1)
  10. {
  11. if (a >= b) return -1; // constraint: a must be greater than b
  12.  
  13. // if strips is not provided, calculate it
  14. if (strips == -1) strips = GetStrips(a, b, f);
  15.  
  16. double h = (b - a) / strips,
  17. acc = 0;
  18.  
  19. for (int i = 0; i < strips; i++) acc += h * f(a + i * h);
  20.  
  21. return acc;
  22. }
  23.  
  24. /// <summary>
  25. /// Return the integral from a to b of function f
  26. /// using the midpoint rule
  27. /// </summary>
  28. public static double MidPoint(double a, double b, Func<double, double> f, int strips = -1)
  29. {
  30. if (a >= b) return -1; // constraint: a must be greater than b
  31.  
  32. // if strips is not provided, calculate it
  33. if (strips == -1) strips = GetStrips(a, b, f);
  34.  
  35. double h = (b - a) / strips,
  36. x = a + h / 2,
  37. acc = 0;
  38.  
  39. while (x < b)
  40. {
  41. acc += h * f(x);
  42. x += h;
  43. }
  44.  
  45. return acc;
  46. }
  47.  
  48. /// <summary>
  49. /// Return the integral from a to b of function f
  50. /// using trapezoidal rule
  51. /// </summary>
  52. public static double Trapezoidal(double a, double b, Func<double, double> f, int strips = -1)
  53. {
  54. if (a >= b) return -1; // constraint: b must be greater than a
  55.  
  56. // if strips is not provided, calculate it
  57. if (strips == -1) strips = GetStrips(a, b, f);
  58.  
  59. double h = (b - a) / strips,
  60. acc = (h / 2) * (f(a) + f(b));
  61.  
  62. for (int i = 1; i < strips; i++) acc += h * f(a + i * h);
  63.  
  64. return acc;
  65. }
  66.  
  67. static int GetStrips(double a, double b, Func<double, double> f)
  68. {
  69. int strips = 100;
  70.  
  71. for (int i = (int)a; i < b; i++)
  72. strips = (strips > f(i)) ? strips : (int)f(i);
  73.  
  74. return strips;
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement