from math import factorial
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
sp.init_printing()
x = sp.Symbol("x")
f = sp.sqrt(1-x**2)
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
:
n = 50
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:
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:
tmp = 0
for i in range(n):
tmp += (coeffs[i] * 1/(i+1) * (1**(i+1) - 0**(i+1))).evalf()
my_pi = 4*tmp
print(my_pi, np.pi)
One important aspect of studying numerical methods: