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

# In[1]:


#centered finite difference to approximate f'(a)
def fd(f, a, h):
    return (f(a+h)-f(a-h))/(2*h)


# In[2]:


from numpy import sqrt
f = lambda x: sqrt(x)
df = lambda x: 1 / (2*sqrt(x))


# In[3]:


a = 2
h = 0.1
x_approx = fd(f, a, h) #appoximation of derivative
x = df(a) #derivative from the analytical expression


# In[4]:


x_approx, x


# In[5]:


#absolute and fractional errors of approximation
E_a = abs(x_approx - x)
E_f = E_a / abs(x)
E_a, E_f


# In[6]:


from numpy import pi
pi


# In[7]:


from numpy import sin
sin(pi) #not exactly 0 because of roundoff error


# In[8]:


0.3 - 3*0.1 #not exactly 0 because of roundoff error


# In[9]:


#10.0**320 #overflows -- error


# In[10]:


10.0**(-330) #underflows


# In[11]:


(3 - 3*1)/10 #exactly 0


# In[12]:


10**400 #integer -- no overflow


# In[13]:


#0/0 #error


# In[14]:


#example of truncation and roundoff errors both affecting the 
#total error in applying a numerical method
from numpy import logspace
hs = logspace(-10, 0, 100)
approx = fd(f, a, hs)
x = df(a) #true value
approx_Ef = abs(approx - x) / abs(x)


# In[15]:


from matplotlib.pyplot import plot, semilogx, loglog, xlabel, ylabel
loglog(hs, approx_Ef)
xlabel('Increment h')
ylabel('Fractional error in derivative computation')


# In[16]:


from numpy import array
v = array([1, 2, 3])


# In[17]:


v


# In[18]:


v.dtype


# In[19]:


array([1, 2, 3.1]).dtype


# In[20]:


array([1, 2, 3.1]).shape


# In[21]:


A = array([[1, 2, 3.1], [2, 5, 1]])


# In[22]:


A.shape[0] #number of rows in the matrix A


# In[23]:


from numpy import zeros
Z = zeros((2, 3))


# In[24]:


from numpy import ones
F = 5 * ones((2, 3))


# In[25]:


F[0, 1] = 3


# In[26]:


F


# In[27]:


from numpy import diag
D = diag([1, 2, 4]) #creates a diagonal matrix


# In[28]:


D


# In[29]:


from numpy import empty
E = empty([2, 2])


# In[30]:


E #has arbitrary values, but can then be assigned to something specific


# In[31]:


B = array([[0.5, 1], [-2, 3], [0, 4]])


# In[32]:


C = A@B #matrix multiplication


# In[33]:


A * B.T #element-by-element multiplication


# In[34]:


T = B.T


# In[35]:


B


# In[36]:


B[0, 1] = 10


# In[37]:


B


# In[38]:


T


# In[39]:


T = B.copy().T
T


# In[40]:


B[0, 1] = 8


# In[41]:


B


# In[42]:


T


# In[43]:


#solving a linear system
M = array([[3., 2.], [1, -1]])
b = array([[7], [-1]])


# In[44]:


M, b


# In[45]:


from numpy.linalg import solve
x = solve(M, b)


# In[46]:


x


# In[47]:


M@x - b #should be a vector of zeros


# In[48]:


from numpy.linalg import inv #matrix inverse
Minv = inv(M)


# In[49]:


Minv


# In[50]:


M@Minv


# In[51]:


Minv@M


# In[52]:


Minv@b


# In[53]:


#inv(array([[1, 2], [2, 4]])) #matrix with no inverse -- error


# In[54]:


#solve(array([[1, 2], [2, 4]]), array([[5], [10]])) #also raises an error


# In[55]:


from numpy.linalg import cond


# In[56]:


#diagonal matrix
cond(diag([1, 2, 4]))


# In[57]:


cond(diag([1, 1, 1]))


# In[58]:


cond(array([[1, 2], [2, 4]])) 
#singular matrix, condition number is infinite
#(but may be returned as ~1/epsilon because of roundoff)


# In[59]:


cond(array([[1+1e-8, 2], [2, 4]]))


# In[60]:


M.shape[0]


# In[61]:


#function to do back substitution
#Ux = b where U is upper triangular
from numpy import empty, sum
def bsub(U, b):
    n = U.shape[0]
    x = empty(n)
    for i in range(n-1, -1, -1):
        x[i] = (b[i] - sum(x[(i+1):n] * U[i, (i+1):n])) / U[i, i]
    return x


# In[62]:


U = array([[2, 1], [0, 2]]) #example
b = array([4, 4])


# In[63]:


x = bsub(U, b)


# In[64]:


U@x #should equal b


# In[65]:


#function to do forward substitution
#Lx = b where L is lower triangular
from numpy import empty, sum
def fsub(L, b):
    n = L.shape[0]
    x = empty(n)
    for i in range(n):
        x[i] = (b[i] - sum(x[0:i] * L[i, 0:i])) / L[i, i]
    return x


# In[66]:


L = array([[2, 0], [3, 2]])
b = array([4, 8])
x = fsub(L, b)


# In[67]:


L@x


# In[68]:


from numpy import zeros
zeros([2, 2])


# In[69]:


#function to find Cholesky factor of a symmetric matrix
#L L' = S
from numpy import zeros, sqrt, sum
def fchol(S):
    n = S.shape[0]
    L = zeros([n, n])
    for j in range(n):
        L[j, j] = sqrt(S[j, j] - sum(L[j, 0:j]**2))
        for i in range(j+1, n):
            L[i, j] = (S[i, j] - sum(L[i, 0:j]*L[j, 0:j])) / L[j, j]
    return L    


# In[70]:


S = array([[1, 2, 3], [2, 5, 7], [3, 7, 14]]) #example
L = fchol(S)
L@L.T #should equal S


# In[71]:


S[(1, 2), :] = S[(2, 1), :]
S


# In[72]:


#LU decomposition of a square matrix
#with row pivoting
#LU = PA
from numpy import eye, argmax, float64
def lud(A):
    n = A.shape[0]
    U = A.astype(float64).copy()
    L = eye(n)
    P = eye(n)
    for i in range(n-1):
        p = i + argmax(abs(U[i:n, i])) #pivot row
        U[(i, p), :] = U[(p, i), :] #interchange rows
        P[(i, p), :] = P[(p, i), :]
        L[(i, p), 0:i] = L[(p, i), 0:i]
        for j in range(i+1, n):
            M = U[j, i] / U[i, i]
            U[j, :] = U[j, :] - M*U[i, :]
            L[j, i] = M
    return P, L, U


# In[73]:


A = array([[0, 2, 2], [1, -2, -1], [4, -2, 4]])
P, L, U = lud(A)


# In[74]:


L@U - P@A #should be all zero

