# -*- coding: utf-8 -*-
"""
Created on Mon Aug  1 14:15:47 2022

@author: Chris

Lab 1 Question 10 - numerical 2nd order derivative
"""
import numpy as np
import matplotlib.pyplot as plt

"""
Function definitions
"""

def myfun(x):
    myfun = np.sin(x)
    return myfun


""" Main Script starts"""

h = np.logspace(-8,-1,100)    # choose range of steps

xrange = [0.1,0.5, 1.0, 1.5]

for x in xrange:
    dfdx2 = (myfun(x+h)-2*myfun(x)+myfun(x-h))/h**2 #numerical 2nd order derivative
    dfdx2_real = -np.sin(x) #analytic solution
    
    err_abs = abs(dfdx2-dfdx2_real) #absolute error
    err_rel = abs(err_abs/dfdx2_real)   #relative error
 
#    plt.loglog(h,err_abs,'.') # plot absolute error
    plt.loglog(h,err_rel,'.') # plot relative error
    
    plt.xlabel('stepsize h')
    plt.show()
    input()

    






