#!/usr/bin/env python
# coding: utf-8

# In[4]:


#example from textbook showing Taylor series approximation of sin(x) about a = 0

from math import factorial
from numpy import linspace, zeros, pi, sin

x = linspace(-pi, pi, 200)
y = zeros(len(x))

labels = ['First Order', 'Third Order', 'Fifth Order', 'Seventh Order']

from matplotlib.pyplot import plot, figure, grid, title, xlabel, ylabel, legend, show

figure(figsize = (10,8))
for n, label in zip(range(4), labels):
    y = y + ((-1)**n * (x)**(2*n+1)) / factorial(2*n+1)
    plot(x,y, label = label)

plot(x, sin(x), 'k', label = 'Analytic')
grid()
title('Taylor Series Approximations of sin(x) of Various Orders')
xlabel('x')
ylabel('y')
legend()
show()


# In[5]:


#function to do n iterations of Newton's method
def newton(f, df, x0, n):
    x = x0
    for i in range(n):
        x = x - f(x)/df(x)
        print(x)
    return x


# In[6]:


f = lambda x: x**3 - 6
df = lambda x: 3*x**2
x0 = 2
n = 6
x = newton(f, df, x0, n)


# In[7]:


6 ** (1/3)


# In[9]:


x ** 3


# In[10]:


from numpy import cos, sin
f = lambda x: cos(x) - x
df = lambda x: -sin(x) - 1
x0 = 0.5
n = 6
x = newton(f, df, x0, n)


# In[11]:


cos(x) - x


# In[12]:


#function to approximate f'(x) using centered finite differences
def fd(f, x, h):
    df = (f(x+h) - f(x-h)) / (2*h)
    return df


# In[16]:


f = lambda x: cos(x)
x = 0.5
h = 0.01
fd(f, x, h)


# In[15]:


-sin(x)


# In[17]:


#function to apply Euler's method for solving an initial value problem
def euler(f, a, b, ya, n):
    h = (b - a) / n
    from numpy import zeros, linspace
    x = linspace(a, b, n+1)
    y = zeros(n+1)
    y[0] = ya
    for i in range(n):
        y[i+1] = y[i] + h * f(x[i], y[i])  
    return x, y


# In[19]:


f = lambda x, y: -y
a = 1
b = 2
ya = 3 #initial value of y
n = 20 #number of steps
x, y = euler(f, a, b, ya, n)
print(x, y)


# In[21]:


#in-class assignment 1
e = 0
x = 0.5
for i in range(10):
    e = e + ((x**i)/factorial(i))
print(e)
from numpy import exp
et = exp(0.5)
print(et)
print(abs(e - et))


# In[ ]:




