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

# In[1]:


#alternatives for importing a function from a library
import numpy
numpy.sqrt(26)


# In[2]:


from numpy import sqrt
sqrt(26)


# In[3]:


import numpy as np
np.sqrt(26)


# In[4]:


#does one iteration of Newton's method
def newton(f, df, a):
    x = a - f(a)/df(a)
    return x


# In[7]:


f = lambda x: x**2 - 26
df = lambda x: 2*x
a = 5


# In[8]:


newton(f, df, a)


# In[9]:


#find cube root of 7
c = lambda x: x**3 - 7
dc = lambda x: 3 * (x**2)
x0 = 2


# In[11]:


#two iterations
x1 = newton(c, dc, x0)
newton(c, dc, x1)


# In[12]:


#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[13]:


from numpy import exp
f = lambda x: exp(x)
a = 1
h = 0.1


# In[14]:


fd(f, a, h)


# In[15]:


#with smaller increment (better approximation)
h = 0.01
fd(f, a, h)


# In[16]:


#one step of Euler's method
#for y' = g(y, x) and y(x0) = y0
def euler(g, x0, y0, h):
    return y0 + h * g(y0, x0)


# In[17]:


g = lambda y, x: y
x0 = 0
y0 = 1
h = 0.5


# In[19]:


#two steps from x=0 to x=1
y1 = euler(g, x0, y0, h)
euler(g, x0+h, y1, h)


# In[25]:


#compute the nth-order term of the Taylor series of sin(x) about 0 
def tsin(x, n):
    from math import factorial
    r = n % 4
    if r == 0:
        return 0
    elif r == 1:
        return (x**n / factorial(n))
    elif r == 2:
        return 0        
    elif r == 3:    
        return (-x**n / factorial(n))


# In[40]:


#tests for this function
assert tsin(1, 0) == 0
assert tsin(1, 1) == 1
assert tsin(1, 2) == 0
assert tsin(1, 3) == -1/6
assert tsin(1, 4) == 0
assert tsin(1, 5) == 1/120
assert tsin(0, 5) == 0


# In[37]:


tsin(1, 3)


# In[41]:


#sum of the first n terms of the Taylor series of sin(x) about 0
def tsin_sum(x, n):
    s = 0
    for i in range(n):
        s = s + tsin(x, i)
    return s


# In[42]:


tsin_sum(1, 10)


# In[43]:


from numpy import sin
sin(1)


# In[48]:


#example of plotting a function using matplotlib
import numpy
import matplotlib.pyplot
u = numpy.linspace(1, 40, 40); v = numpy.log(u); matplotlib.pyplot.plot(u, v, '-*')
matplotlib.pyplot.xlabel('u'); matplotlib.pyplot.ylabel('log of u'); 
matplotlib.pyplot.title('Example')


# In[ ]:




