Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2019
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. import math
  2. import numpy as np
  3.  
  4.  
  5. def left_riemann_sum(f, a, b, num_rects):
  6. interval_length = float(b - a)
  7. dx = interval_length / num_rects
  8. riemann_sum = 0
  9.  
  10. for i in range(0, num_rects):
  11. riemann_sum += f(a + i * dx) * dx
  12.  
  13. return riemann_sum
  14.  
  15. print(round(left_riemann_sum(math.sin, 0, 2*math.pi, 100), 5))
  16. print(round(left_riemann_sum(lambda x: 1, 0, 1, 100), 5))
  17. print(round(left_riemann_sum(math.exp, 1, 2, 100), 5))
  18. print("\n\n")
  19.  
  20. def joe_riemann_sum_lb(f, a, b, n):
  21. deltax = float(b-a)/n
  22. area = 0
  23.  
  24. for i in range(0, n):
  25. area += f(a + i*deltax) * deltax
  26.  
  27. return area
  28.  
  29.  
  30. print(round(joe_riemann_sum_lb(math.sin, 0, 2*math.pi, 100), 5))
  31. print(round(joe_riemann_sum_lb(lambda x: 1, 0, 1, 100), 5))
  32. print(round(joe_riemann_sum_lb(np.exp, 1, 2, 100), 5))
  33. print("\n")
  34.  
  35.  
  36. def joe_riemann_sum_ub(f, a, b, n):
  37. deltax = float(b-a)/n
  38. area = 0
  39. a = a + deltax
  40.  
  41. for i in range(0, n):
  42. area += f(a + i*deltax) * deltax
  43.  
  44. return area
  45.  
  46. print(round(joe_riemann_sum_ub(np.exp, 1, 2, 100), 5))
  47. print("\n")
  48.  
  49. def joe_riemann_sum_mp(f, a, b, n):
  50. deltax = float(b-a)/n
  51. area = 0
  52.  
  53. mp = (a + deltax/2.0)
  54.  
  55. for i in range(0, n):
  56. area += f(mp + i*deltax) * deltax
  57.  
  58. return area
  59.  
  60. print(round(joe_riemann_sum_mp(np.sin, 0, 2*np.pi, 100), 5))
  61. print(round(joe_riemann_sum_mp(lambda x: np.ones_like(x), 0, 1, 100), 5))
  62. print(round(joe_riemann_sum_mp(np.exp, 1, 2, 100), 5))
  63. print("\n")
  64.  
  65.  
  66. def joe_riemann_sum_mp_numpy(f, a, b, n):
  67. x = np.linspace(a, b, n)
  68. deltax = float(b-a)/n
  69. area = 0
  70. aplus1 = a + deltax
  71.  
  72. mp = (a + deltax/2.0)
  73.  
  74. #or funct = lambda i : f(mp + i*deltax) * deltax
  75. # y = funct(x)
  76. # np.sum(y)
  77. #2.77321
  78.  
  79. for i in np.nditer(x):
  80. area += f(mp + i*deltax) * deltax
  81.  
  82. return area
  83. print(round(joe_riemann_sum_mp_numpy(np.exp, 1, 2, 100), 5))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement