Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- def estimate_taylor_series(a_k, x, precision=1E-11):
- max_k = 0
- current = math.fabs(a_k(x, max_k))
- while current > precision:
- max_k += 1
- current = math.fabs(a_k(x, max_k))
- running_sum = 0
- for k in range(max_k):
- running_sum += a_k(x, k)
- return running_sum
- def estimate_cos(x, precision=1E-11):
- return estimate_taylor_series(
- lambda x, k: ((-1)**k / math.factorial(2*k)) * (x) ** (2 * k),
- x,
- precision)
- def estimate_sin(x, precision=1E-11):
- return estimate_taylor_series(
- lambda x, k: ((-1)**k / math.factorial(2*k+1)) * (x) ** (2*k + 1),
- x,
- precision)
- print("Comparison: ")
- print("estimated cos:",estimate_cos(3.04))
- print("calculated cos:",math.cos(3.04))
- print("estimated sin:", estimate_sin(3.04))
- print("calculated sin:", math.sin(3.04))
- # expected:
- # Comparison:
- # estimated cos: -0.9948439033600767
- # calculated cos: -0.9948439033594595
- # estimated sin: 0.1014179863214654
- # calculated sin: 0.10141798631660187
Add Comment
Please, Sign In to add comment