Guest User

Untitled

a guest
Sep 22nd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. import math
  2.  
  3. def estimate_taylor_series(a_k, x, precision=1E-11):
  4. max_k = 0
  5. current = math.fabs(a_k(x, max_k))
  6. while current > precision:
  7. max_k += 1
  8. current = math.fabs(a_k(x, max_k))
  9.  
  10. running_sum = 0
  11. for k in range(max_k):
  12. running_sum += a_k(x, k)
  13.  
  14. return running_sum
  15.  
  16. def estimate_cos(x, precision=1E-11):
  17. return estimate_taylor_series(
  18. lambda x, k: ((-1)**k / math.factorial(2*k)) * (x) ** (2 * k),
  19. x,
  20. precision)
  21.  
  22. def estimate_sin(x, precision=1E-11):
  23. return estimate_taylor_series(
  24. lambda x, k: ((-1)**k / math.factorial(2*k+1)) * (x) ** (2*k + 1),
  25. x,
  26. precision)
  27.  
  28. print("Comparison: ")
  29. print("estimated cos:",estimate_cos(3.04))
  30. print("calculated cos:",math.cos(3.04))
  31.  
  32. print("estimated sin:", estimate_sin(3.04))
  33. print("calculated sin:", math.sin(3.04))
  34.  
  35. # expected:
  36.  
  37. # Comparison:
  38. # estimated cos: -0.9948439033600767
  39. # calculated cos: -0.9948439033594595
  40. # estimated sin: 0.1014179863214654
  41. # calculated sin: 0.10141798631660187
Add Comment
Please, Sign In to add comment