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

# In[2]:


#from lab 1
#centered finite difference approximation of first derivative
#at a with step size h
def fd(f, a, h):
    return (f(a+h) - f(a-h)) / (2*h)


# In[4]:


#example in slides
f = lambda x: x ** 1.8
x = 0.5
h = 0.1
dxe = fd(f, x, h) #approximation


# In[7]:


df = lambda x: 1.8 * (x ** 0.8)
dx = df(x) #actual value


# In[8]:


#absolute error
abs(dxe - dx)


# In[9]:


#fractional error
abs(dxe - dx) / abs(dx)


# In[10]:


dxe, dx


# In[26]:


#first method from slide
from math import factorial, isinf
for n in range(1000):
    try:
        (n ** n) / factorial(n)
    except OverflowError:
        print(n)
        break


# In[27]:


#second method from slide
for n in range(1000):
    try:
        r = 1
        for i in range(n):
            r = r * (n / (n-i))
        if isinf(r):
            print(n)
            break
    except OverflowError:
        print(n)
        break


# In[29]:


0.3/0.1


# In[31]:


#compute the nth-order term of the Taylor series of exp(x) about 0 
def texp(x, n):
    return (x**n / factorial(n))    


# In[32]:


va = 0
for i in range(50):
    va = va + texp(-7, i)


# In[33]:


va


# In[34]:


vb = 0
for i in range(50):
    vb = vb + texp(7, i)
vb = 1 / vb


# In[35]:


vb


# In[36]:


from math import exp
v = exp(-7)


# In[38]:


#relative errors of the two estimates
ra = abs(va - v) / abs(v)
rb = abs(vb - v) / abs(v)
ra, rb


# In[ ]:




