# coding: utf-8
# # Computing $\pi$ with Taylor
# In[16]:
from math import factorial
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
sp.init_printing()
x = sp.Symbol("x")
# In[17]:
f = sp.sqrt(1-x**2)
# In[18]:
pts = np.linspace(0, 1, 100)
f_values = np.array([f.subs(x, pt) for pt in pts])
plt.plot(pts, f_values)
# Get the Taylor coefficients into a list `coeffs`:
# In[43]:
n = 50
# In[44]:
coeffs = []
for i in range(n):
coeffs.append(f.diff(x, i).subs(x, 0)/factorial(i))
coeffs
# For comparison: Here's the full Taylor polynomial:
# In[45]:
taylor = 0
for i in range(n):
taylor += f.diff(x, i).subs(x, 0)/factorial(i) * x**i
taylor
# Now compute an approximate integral:
# In[46]:
tmp = 0
for i in range(n):
tmp += (coeffs[i] * 1/(i+1) * (1**(i+1) - 0**(i+1))).evalf()
# In[47]:
my_pi = 4*tmp
print(my_pi, np.pi)
# * What do you think?
# * Did that work well?
# * Did it have a right to work well?
# * One important aspect of studying numerical methods:
#
# * When do things like this work well/efficiently?
# * When do they not?
# * Why?
# In[ ]: